29-Basic Operations on File Objects

29-Basic Operations on File Objects

# The three steps of file operation: open, read and write, and close
# cp/etc/passwd/tmp
f = open('/tmp/passwd') # Open the plain text file in r by default
data = f.read() # read() read all the content
print(data)
data = f.read() # With the progress of reading and writing, the file pointer moves backward.
# Because the first f.read() has moved the file pointer to the end, there will be no data when reading again
# So data is an empty string
f.close()

f = open('/tmp/passwd')
data = f.read(4) # read 4 bytes
f.readline() # read to the end of a newline/n
f.readlines() # Read out each line of data and put it in the list
f.close()

###############################
f = open('/tmp/passwd')
for line in f:
    print(line,)
f.close()

#############################
f = open('picture address','rb') # open non-text file to add parameter b
f.read(4096)
f.close()

#################################
f = open('/tmp/myfile','w') #'w' open the file, if the file does not exist, create
f.write('hello world!\n')
f.flush() # Immediately synchronize the data in the cache to the disk
f.writelines(['2nd line.\n','new line.\n'])
f.close() # When closing the file, the data is saved to disk

#############################
with open('/tmp/passwd') as f:
    print(f.readline())

########################
f = open('/tmp/passwd')
f.tell() # View the position of the file pointer
f.readline()
f.tell()
f.seek(0, 0) # The first number is the offset, and the second number is the relative position.
              # Relative position 0 means the beginning, 1 means the current, 2 means the end
f.tell()
f.close()
Reference: https://cloud.tencent.com/developer/article/1334352 29-Basic File Object Operations-Cloud + Community-Tencent Cloud