Home  >  Article  >  Backend Development  >  python introduction to file operation process

python introduction to file operation process

零下一度
零下一度Original
2017-06-30 13:38:012137browse

File operation process

1. Open the file, get the file handle and assign it to a variable
2. Operate the file through the handle
3. Close the file

Open the file

open() will return a file object. The basic syntax format is as follows:

open(filename, mode)

 1 ''' 2 data = open("Nunber",encoding="utf-8").read() 
 3 上面这种直接将内容完全赋值给变量的方法,就无法将这个变量当做对象处理。这种方式只会打开文件读取后 4 马上关闭。所以请用下面的方式 5 '''  6 f = open("Nunber",encoding="utf-8") 
 7 文件句柄(f):将文件名称,文件大小,文件长度,文件指针等封装成一个可操作对象,这个可操作对象就是f 
 8 first = f.read() 9 second = f.read()10  11 print(first)12 print("__________打印第二遍____________")13 print(second)14 f.close()

Execution result

一二三四五
二三四五六七
三四五六七八九
45678901234567890
56789012345678901
67890123456789012
78901234567890123
89012345678901234
90123456789012345
01234567890123456
__________打印第二遍____________
进程已结束,退出代码0

About File pointer:

second The second reassignment did not print. This is because after open opens the file, read reads one line and then reads another line to open it. The first The second read has moved the file pointer in the handle to the last position of the file. The file pointer is like the cursor in word, so nothing can be read during the second read.
(File) Method
 1 # f.read() 不加参数读取全部,参数打印指定字节数 2 
 f = open("Nunber","r",encoding="utf-8") 3 
 my_read = f.read(21) 4 print(my_read) 5  6 
 # f.readline() 不加参数读取一行,参数打印指定这一行的字节数 7 
 my_readline = f.readline(8) 8 print(my_readline) 9 10 # f.tell()显示文件指针位置11 
 print(f.tell())12 13 # f.seek()控制文件指针位置14 f.seek(0)15 print(f.tell())16 17 
 #f.close()关闭文件18 f.close()19 20 
 # f.readlines() 不加参数按行读取所有行,并将每行作为一个元素存为类表。参数大于每行数字节21 
 # 数就将下一行作为元素存入列表。22 23 f = open("Nunber",encoding="utf-8")24 my_readlines = f.readlines(40)25 f.close()26 print(my_readlines)

The above is the detailed content of python introduction to file operation process. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn