As a development language, Python must inevitably manipulate external files, such as reading external files and performing calculations, such as storing the results of operations in local files. The following shows common python methods for manipulating files.

inPythonTo manipulate a file, you need to remember 1 function and 3 methods

The serial number Function/method instructions
01 open Open the file and return the file action object
02 read Read the contents of the file into memory
03 write Writes the specified content to a file
04 close Close the file
  • openThe function opens the file and returns the file object
  • read/write/closeAll three methods need to be passedThe file objectTo invoke the

1. Create (open) a file and close it

1.1 In Python, using the open function, you can open an existing file or create a new file if the file does not exist.

The format is as follows: open(” file name “, access mode), the default directory is created in the current program directory

Fo =open(“myfile.doc”,’w’)

Common access mode usage:

Warm tip: Frequently moving the file pointer will affect the read and write efficiency of the file. During the development, more files will be operated in read-only and write-only mode

Access pattern instructions
r Open the file in read-only mode. The pointer to the file will be placed at the beginning of the file. This is the default mode.
w Opening a file is for writing only. Overwrite the file if it already exists. If the file does not exist, create a new one.
a Open a file for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file to write to.
rb Open a file in binary format for read-only use. The file pointer will be placed at the beginning of the file. This is the default mode.
wb Open a file in binary format only for writing. Overwrite the file if it already exists. If the file does not exist, create a new one.
ab Open a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file to write to.
r+ Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
w+ Open a file for reading and writing. Overwrite the file if it already exists. If the file does not exist, create a new one.
a+ Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. Files open in append mode. If the file does not exist, create a new file for reading and writing.
rb+ To open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.
wb+ To open a file in binary format for reading and writing. Overwrite the file if it already exists. If the file does not exist, create a new one.
ab+ Open a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.

1.2 Because the file is read by flow, like the valve of a water pipe. Every time the operation file is read, the valve must be opened () first, so it must be closed when used. Fo.close() can be used directly.

F = open('test.txt', 'w') f = open('test.txt', 'w')Copy the code

2. Read /write the file

1. Write data: Use write(” content “) to write data to a file. Note: If the file does not exist, create it.

f = open('write_demo.txt'.'w') Open a file and write data to it. If no, create one.
print ("File name:", f.name)  #f.name Specifies the name of the printed file, with the extension
f.write('hello ,I am writing ') # Note that write is to empty the contents of the file and then write.
f.close() # close file
Copy the code

2. Read data: Use read(num) to read data from a file. Num indicates the length (number of characters) of the data to be read from the file. If num is not passed or is negative, all data in the file is read. Note:

  • If open is to open a file, then you don’t have to write the open mode, that is, just writeopen('aaa.txt')
  • If read is used more than once, subsequent reads with read begin where they left off
  • Note: By default, the read () method reads the entire contents of the file into memory at once, although you can specify the number of characters to read. If the file is too large, it can be very heavy on memory
#1. Prepare documents
f = open('write_demo.txt'.'w+') Create a new file,w+ indicates that it is used for reading and writing
f.write('Hello ABC Wang Xiaoming, hello')  # write content
f.close() # file close

#1. File reading begins
f=open("write_demo.txt".'r')
content=f.read(3)  #3 reads three characters, albeit byte. But the actual return by character when there is Chinese
print("Contents read: %s"%content)
content1=f.read(1)  If read() is used to read all, then read(num) is used to read nothing. Return empty string
print("Read file contents: %s"%content1)
content2=f.read(5)
print("Read file contents: %s"%content2)
f.close()
C Wang Xiaoming, "hello" a "hello" B "hello" C wang Xiaoming, "hello"
Copy the code

Readlines () reads the entire file as a single line, reading all the lines (up to the terminator EOF) and returning a list with each line as an element.

f = open('test.txt'.'r')
content = f.readlines() Read all lines in the file and store them in a list by line, type string
print(type(content))  Print the value type of the read result, stored as a list

i=1  # Walk through the list to display the contents of the read, divided by the original file lines.
for temp in content:
    print("%d:%s"%(i, temp))
    i+=1
f.close()
''' 
      
        1:hello,world, 2:this is a demo '''
      
Copy the code

4. Read data: readline(), read the data in the original file by line, (line partition is \n). Only one line is read at a time. If there are multiple reads, the offset from the next read is the offset from the previous read.

f = open('test.txt'.'r')
content = f.readline()
print("First read :%s"%content)

content = f.readline()
print("Second read :%s"%content)

f.close()
First read :hello,world, second read :this is a demo.
Copy the code

Unified statement: About the original blog content, there may be some content reference from the Internet, if there is an original link will be quoted; If can not find the original link, in this statement if there is infringement please contact to delete ha. About reprint blog, if have original link will declare; If can not find the original link, in this statement if there is infringement please contact to delete ha.