The third chapter mainly introduces simple file reading and simple exception handling operation.
Start by creating a file directory: HeadFirstPython\chapter3
Download the file you need to use at head first Pythong official website: sketch.txt, and put it in the previously built directory.
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 the Python interactive environment (Pyhton idle), you can use some of the following commands to do some file manipulation:
>>> Import OS # importing OS from standard library>>> os.getcwd () # Gets the current working directory, similar toLinuxUnder the PWD 'D: \\program\\Python34 '>>> Os.chdir ("D:\code\python\HeadFirstPython\chapter3") # Switch working directory >>> 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 ":", so consider optimizing at the output. When the file is processed, there will be a corresponding problem, such as some lines in the file does 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. There are two ways to deal with these anomalies:
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, captured and then related operations.
The first way of thinking:
import osif os.path.exists(‘sketch.txt‘): data = open(‘sketch.txt‘) forin data: 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(‘文件不存在!‘)
Second idea: 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 split, the function prototype is str.split(sep=None, maxsplit=-1)
, it contains two parameters, the first is to use the separator, the second is the maximum number of splits. 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, while creating an iterator, you can read the file by line
3. readline()
: Read a line of the file
4 seek()
: Re-point the iterator to the beginning of the file (first line)
5. close()
: Close Open File
6 find()
: Finds the position of the substring in the string, does not exist then returns-1
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Head First Python Chapter3: file read and exception handling