Common file operations

# f.write() #String write to file
#
# f.writelines #Write a string of strings to a file. The sequence can be any iterable that yields a string, usually a list of strings
#
# f.read([size]) #Read everything in the file by default, you can specify size (bytes)
#
# f.readline([size]) #By default, one line is read at a time, and a trailing newline character is retained in the string.
#
# f.readlines([size]) #By default, the contents of the file will be saved in the list
#
# f.flush() #Write the contents of the buffer to disk
#
# f.tell() #Display the current file pointer position
#
# f.close() #Close the open file
#
# f.seek() # Perform pointer offset operation on the file, there are three modes,
#
# Generally not binary, the initial position can only be filled with 0 seek(0,0) move to the beginning of the file by default or abbreviated as seek(0)
#
# rb and rb+ can only use negative seek(x,1) to move back x (positive number) bytes from the current pointer position. If x is a negative number, the current position is moved forward by x bytes
#
# A Chinese has three bytes, and it has to move three by three. Otherwise, seek(x,2) means to move x (positive number) bytes forward and backward from the end of the file. If x is negative, it is from the end move forward x bytes

f = open("file2.txt",'w+',encoding='utf-8')
f.write("I love python\n")
f.write("python is the most beautiful language in the world!\n")
f.write("python the most beautiful language in the world?")
print(len(f.read())) #The total length of the file is 89
print(f.tell()) #After reading the file, the file pointer position is 89
f.seek(0,0) #Offset back to the file header
print(f.readline()) #Print out one line in the file (the first line)
print (f.tell()) #Display the current position of the file pointer
print(f.readline()) #Print another line (should be 2 bytes less)
print(f.tell()) #Display the current pointer position
print(f.readline()) # print the next line
print(f.tell()) #Display the current pointer position
f.seek(57,0) #Offset 9 characters forward from the tail
print(f.tell()) #Display the current pointer position
print(f.readline()) #Print out the content
f.close()
# Use r+ to open and write, be sure to pay attention to the cursor position, if there is text, it will be overwritten, because the cursor starts from the beginning

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325900431&siteId=291194637