File reading and writing of python notes

'''
file operations
Parameter 1: file name, can be the absolute path of the file
Parameter 2: option permission r read w write b binary a append
'''

# global declaration
import codecs

ENCODEING = "utf-8" #must be uppercase
# python3 needs to specify character encoding encoding="utf-8"

# read file contents
f = open("1.txt","r",encoding=ENCODEING)
# Common operation methods of file object f
print(f.read()) # Read all the contents of the file and return a string
print(f.tell()) # Returns the file cursor position
# The cursor position after the beginning of this line is the same as indicating that the previous line of code has been read to the end, and the data will not be retrieved later
print(f.readline()) #Read each line of the file and return the string data of each line
print(f.tell()) # Returns the file cursor position


# f.seek(offset,whence) # offset offset whence 0 starts, 1 is the current position, 2 ends
# help(f.seek()) # Control the file cursor, the file needs to be opened in b mode, positive number, backward offset, negative number, forward offset
f.seek(0,0) #return to the starting position
print(f.tell()) # Returns the file cursor position

print(f.readlines()) # Read the contents of the file and return a list, each line is an element
print(f.tell()) # Returns the file cursor position

for line in f.readlines():
    print(line)

for i,line in enumerate(f.readlines()):
    print("Line {0}: {1}".format(i,line)) #Can output line number
print(f.tell()) # Returns the file cursor position
print(f.name) #file name
print(f.fileno()) #file descriptor
print(f.encoding) #File encoding

print(f.close()) #Close the file, return the bool value to determine whether the file is closed


# write file contents
fw = open("2.log","w",encoding=ENCODEING)
data = "hello world \n why don't you go to heaven\n no do no die"
fw.write(data) #Write the string data to the file, only accept string parameters
fw.truncate(20) # How many bits are reserved, can only be used for writing, clear the file, size represents where to clear it
fw.close()

print("###########################")
# Not considering whether to close, it will close itself
with codecs.open("1.txt","r",encoding=ENCODEING) as f:
    print(f.read())
# most commonly used

with codecs.open("3.log","w",encoding=ENCODEING) as f:
    f.write(data)

Guess you like

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