Python read and write files in the computer language is widely used, if you want to know the application of the program, the following article will give you a detailed introduction of the relevant content, you will be helpful in the process of learning later, we will detail its application.
First, open the file
Python read and write files in the computer language is widely used, if you want to know the application of the program, the following article will give you a detailed introduction of the relevant content, you will be helpful in the process of learning later, we will detail its application.
The code is as follows:
- f = open ("D:\test.txt", "W")
Description
The first parameter is the file name, including the path, and the second argument is the open mode
' R ': Read-only (default. Throws an error if the file does not exist)
' W ': Write-only (if the file does not exist, the file is created automatically)
' A ': Append to end of file
' r+ ': Read and Write
If you need to open the file in binary mode, you need to add the character "B" after mode, such as "RB", "WB", etc.
Second, read the content
- F.read (size)
The parameter size indicates the number of reads, which can be omitted. If the size parameter is omitted, all contents of the file are read.
- F.readline ()
Reads the contents of a file line
- F.readlines ()
Read all rows into the array inside [line1,line2,... linen]. This approach is often used to improve efficiency by avoiding the loading of all file content into memory.
Third, write the file
- F.write (String)
Writes a string to the file, and if the write ends, you must add "\ n" after the string, and then F.close () to close the file
Iv. content positioning in the document
- F.read ()
After reading, the file pointer reaches the end of the file, and if you do it again f.read () will find empty content, and if you want to read everything again, you must move the anchor pointer to the beginning of the file:
- F.seek (0)
The format of this function is as follows (in bytes):
- F.seek (offset, from_what)
From_what represents the start of the read position, offset means moving from from_what to a certain distance, such as F.seek (10, 3) is positioned to the third character and then 10 characters later. A from_what value of 0 indicates the beginning of the file, which can also be omitted, and by default 0 is the beginning of the file. The following gives a
- f = open ('/tmp/workfile ', ' r+ ')
- f.write (' 0123456789abcdef ')
- f.seek (5) # go to the 6th byte in the file
- f.read (1)
- ' 5 '
- Span style= "FONT-SIZE:16PX;" >f.seek ( -3, 2) # go to the 3rd byte before the end
- f.read (1)
- ' d '
-  
Python read and write files in the five steps of actual operation