python file operation

python file operation

File mode

r ා read only mode, locate to the beginning of the file, default
r + ා read write mode, locate to the beginning of the file, and write
w ා read mode. When it is opened, the contents of the file will be emptied and cannot be read
w + ා open read / write mode, locate to the beginning, and empty the contents when opening the file
a ා open in write mode and locate to the end of the file. It is an append operation and cannot be read
a + ා read / write mode, locate to the end of the file and append

Relevant operation methods

f = open(r'Route')
f.read()    #Returns all the contents of the file. The type is string
f.write()
f.flush()   #Commit the contents of the buffer
f.seek(Offset, 0/-1)        #Move file pointer
f.tell()    #Find pointer position
f.readline()    #Return one line at a time, the parameter is displayed by byte
f.readlines()   #Returns the contents of the file in the form of a list, including line breaks and removing line breaks [i.rstrip() for i in f.readlines()]
f.close()   #Close file
f.name()    #Print file name
f.next()    #Next iteratable object
f.mode      #Current mode

Example of operation

f = open(r'/mnt/file','r')
print f.read()  #Read file contents

hello !
I am 20 years old
I am a boy

f = open(r'/mnt/file','r+')
f.write('aaa')  #Write content
f.flush()       #Commit what you write, that is, write to the hard disk
print f.tell()  #Show current pointer position
f.seek(0,0)     #Move file pointer
print f.read()

aaalo !
I am 20 years old
I am a boy

f = open(r'/mnt/file','a+')     #Append at the end of the file
print f.read()

aaalo !
I am 20 years old
I am a boy

aaa

f = open(r'/mnt/file','r')
print f.tell()
print f.readline()  #Read line by line, the pointer position will move to the current position
print f.tell()
print f.readline()
print f.tell()
print f.readline()

f.seek(0,0)
print f.readlines() #Returns the contents of the file in the form of a list, including line breaks and removing line breaks [i.rstrip() for i in f.readlines()]
f.close()

0
aaalo !
8
I am 20 years old
26
I am a boy
['aaalo !\n', 'I am 20 years old\n', 'I am a boy\n', '\n', 'aaaaaaaaaaaa']

f = open(r'/mnt/file','r')

print f.readlines()
print f.name        #Display file name
print f.mode        #Show current mode
f.close()

['aaalo !\n', 'I am 20 years old\n', 'I am a boy\n', '\n', 'aaaaaaaaaaaa']
/mnt/file
r

with open(r'/mnt/file','r') as f:   #Security context, operation complete auto save

    print f.readlines()

print f.closed

['aaalo !\n', 'I am 20 years old\n', 'I am a boy\n', '\n', 'aaaaaaaaaaaa']
True

Tags: Python

Posted on Sun, 03 May 2020 08:13:40 -0400 by renj0806