Home > Article > Backend Development > python introduction to file operation process
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:
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!