read read the entire contents of the file, the default mode is read, it is not necessary to specify modes:
f = open('test2.py',encoding='utf8') data = f.read() print(data)
f.close()
Single line redline read the file, when printing plus end = '' Otherwise there will be a space:
f = open('test2.py',encoding='utf8') data = f.readline() data1 = f.readline() print(data,end='') print(data1,end='')
f.close()
Readlines read the entire contents of a list of ways to print each line, each element is a row
f = open('test2.py',encoding='utf8') data = f.readlines() print(data)
f.close()
write write if the file exists is empty, if there is no new file is created, the file contents must be a string :
f = open('test3.py','w',encoding='utf8') f.write("写文件") f.close()
writelines written in the form of a list, write multiple lines when I remember to add \ n
f = open('test3.py','w',encoding='utf8') f.writelines(["dsad\n","dsad\n"]) f.close()
a append operation:
f = open('test3.py','a',encoding='utf8') f.writelines(["dsad\n","dsad\n"]) f.close()
r + opened readable and writable, writing time to start writing from the beginning of where the cursor
f = open('test3.py','r+',encoding='utf8') print(f.read()) f.writelines(["dsad\n","dsad\n"]) f.close()
with as colleagues open multiple files, do not need to close to close the file, \ newline
with open('test3.py','r',encoding='utf8') as f,\ open('test2.py','r',encoding='utf8') as g: print(f.read()) print(g.read())