Head First Python Learning Note-chapter3: File read and exception handling

Source: Internet
Author: User
Tags function prototype

The third chapter mainly introduces simple file reading and simple exception handling operation.

First set up the file folder: HeadFirstPython\chapter3 in the head Pythong official site to download the required files: sketch.txt, and put into the previously built folder.

Related syntax Read file
the_file = open(‘sketch.txt)  # 打开文件,获取到文件对象# 对文件里的数据进行一些处理the_file.close() # 关闭文件
Exception capture
import systry:    # 可能会出现异常的代码    f = open(‘myfile.txt‘)    s = f.readline()    i = int(s.strip())# 对异常进行处理# 相似于Java中的catch块exceptas# 能够指定待捕获的异常    print("OS error: {0}".format(err))except ValueError:    pass# 不做不论什么操作,直接跳过except:    print("Unexpected error:", sys.exc_info()[0])
Get files in an interactive environment

In a python interactive environment (Pyhton idle), you can use some of the following commands for file manipulation:

>>>  Import OS # importing OS from standard library>>> os.getcwd () # Gets the current working folder. Similar toLinuxUnder the PWD 'D: \\program\\Python34 '>>> Os.chdir ("D:\code\python\HeadFirstPython\chapter3") # Switch working folder >>> os.getcwd () 'D: \\code\\python\\Headfirstpython\\chapter3 ' >>> Data = Open('sketch.  TXT ') # Open file, get to file object, equivalent to an iterator iterator>>> Print ( data. ReadLine(), end= "") # reads a line of files,data. ReadLine() Mans: isThis is the right argument?>>> print ( data. ReadLine(), end= "") Other Mans:I ' veTold you Once.>>> data. Seek(0) # to get data back to the beginning of the file0# Use for loop to get each line of the file>>> for Eachlineinch  data:Print (eachline,end="")
Further processing of the data: exception handling

Look at the data in the file and find that each line is delimited with ":". Therefore, the optimization is considered at the output. A corresponding problem occurs when the file is processed. For example, some of the lines in the file do not contain ":", then run throws an ValueError exception, when the file does not exist or read failure, it will be thrown IOError , and so on. Face these anomalies. There are two ways to deal with this:
1. Consider the possible anomalies in the program in advance and deal with them in order to avoid the occurrence of anomalies.
2. Use the exception capture mechanism: Let the exception occur, but the exception is captured. Capture and then do the related operations.

The first way of thinking:
import  osif  os.path.exists (): data = open () for  each_line in  data: Span class= "Hljs-keyword" >if  each_line.find ( ': ' )! =- 1 : (role, Line_spoken) = Each_line.split ( ': ' , 1 ) print (role, End=) print (  ' said: ' , End= ") print (Line_spoken,end=") data.close () else : Print (  file does not exist! 

‘)

Another way of thinking: catching Exceptions:
try: data = open(‘sketch2.txt‘) for each_line in data: # if each_line.find(‘:‘) != -1: try: (role, line_spoken) = each_line.split(‘:‘, 1) print(role, end=‘‘) print(‘ said: ‘, end=‘‘) print(line_spoken,end=‘‘) except: pass # 不做不论什么操作。直接跳过 data.close()except: print(‘文件不存在‘)
Related knowledge points

1, split() : The string is cut. The function prototype is str.split(sep=None, maxsplit=-1) , it consists of two parameters, the first is the use of the cut, the second is the maximum number of cuts. Such as:

>>>' a '. Split (', ')[' 1 ',' 2 ',' 3 ']>>>' a '. Split (', ', maxsplit=1)[' 1 ',' 2,3 ']>>>' 1,2,,3, '. Split (', ')[' 1 ',' 2 ',"',' 3 ',"']>>>' 1 2 3 '. Split () [' 1 ',' 2 ',' 3 ']>>>' 1 2 3 '. Split (maxsplit=1)[' 1 ',' 2 3 ']>>>' 1 2 3 '. Split () [' 1 ',' 2 ',' 3 ']

2 open() : Used to read the file, create an iterator at the same time. Ability to read files by line
3. readline() : Read a line of the file
4 seek() : The iterator again points to the beginning of the file (the first line)
5. close() : Close Open File
6 find() : Find the position of the substring in the string. Does not exist then returns-1

Head First Python Learning Note-chapter3: File read and exception handling

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.