1 File operation... 1
1.1 Open and close files... 1
1.1.2 open function... 1
1.2 Properties of File Objects in Files... 1
1.2.1 Attribute... 1
1.2.2 Method... 2
1.2.3 mode='xx'attribute details... 4
1.3 OS operation files... 6
1 File Operation
1.1 Open and close files
1.1.2 open function
file = open(file_name [,mode][,buffering]
eg: file = open("test.txt",mode = 'r',encoding = 'utf-8')
Details of parameters:
file_name: File name
mode: This parameter is optional and read-only by default (r). For details, see:
https://www.runoob.com/python/python-files-io.html
Enoding: The encoding of files
How to open a file
Note: f.close() must be written at last. Close the file. You can't read it after closing.
1.2 Properties of File Objects in Files
1.2.1 Attribute
file = open('a.txt', mode = 'r' , encoding = 'utf-8')
Close the file.close file and return true, otherwise return false
file.name returns the file name
Fle.mode returns the access mode of the opened file
1.2.2 Method
Note: When you finish writing, you must refresh it and close it.
(1) write() method:
The write() method can write any string to an open file. Note: Python characters can be binary data, not just text.
The write() method does not automatically add a newline character (' n') at the end of the string.
def test3(): f = open("day008/day_008_txt1",mode='w',encoding="utf-8") f.write('Mencius moved three times, and Mencius'mother chose to be good.\n educational environment,Multiple relocations') #Documentation "\n" The function is to change lines. write()Method does not automatically change lines f.flush() #refresh buffer #result = f.read() #This sentence is wrong and cannot be read, because mode='w', read-only mode f.close() #Close files test3()
(2) read() method: read a string from an open file
def test1(): # Read operation f = open('day008/day_008_txt' , mode = 'r',encoding='utf-8') result = f.read() print(result) f.close() # Be sure to remember to write close,And write it to the end. test1()
read(n) reads n characters. If the file is not closed, it will not read when it is read, but will start reading at the last cursor. In fact, all those with'b'are processed non-text. (Contains the following)
Note: In text mode, use "r" and "w" modes without encoding and decoding. But in non-text files, such as videos, music, etc., use'wb'and'rb', because
It is impossible to operate with `w'and `r'. Actually,
(3) close() method:
The close() method of the File object refreshes any unwritten information in the buffer and closes the file so that it cannot be written again after closing.
(4) See () method: Used to move the file to read the pointer to the specified location, that is, the cursor.
Syntax: file.seek(offset[,whence])
Offset: initial offset
whence: Optional, default value is 0. Represents where to start offset; 0 represents the beginning, 1 represents the current location, and 2 represents the end of the file.
_tell(): Get the current position of the cursor
The file.tell() method returns the current location of the file, that is, the current location of the file pointer.
day008/day_008_1.txt file content The moon of Qin shines yet over the passes of Han, The Long March has not been returned. But to make Longcheng fly in, Don't teach Huma to Duyin Mountain.
def test13(): f = open('day008/day_008_1.txt',mode='r',encoding='utf-8') print(f.name)#file name line = f.readline()#Read a row of data in a file print('The data read is:%s'%(line)) #Get the current file location path = f.tell() print('Current position:%d'%path) f.close()#Close files test13()
Result:
_truncate(): truncate files
The file. truncate ([size]) method is used to truncate a file. If there is an optional parameter size, it means that the truncated file is size characters. If no size is specified, it is truncated from the current position; after truncation, all characters after size are deleted.
Note: deeping-bug: In r + mode, if you read the content, no matter how much you read, how many cursors are displayed. Rewriting or manipulating files is done at the end.
1.2.3 mode='xx'attribute details
t |
|
Text mode (default). |
x |
|
Write mode, create a new file, if the file already exists, it will report an error. |
b |
|
Binary mode. |
+ |
|
Open a file for updates (readable and writable). |
U |
|
General Line Break Mode (not recommended). |
r |
|
Open the file read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode. |
rb |
|
Open a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode. Usually used for non-text files such as pictures. |
r+ |
|
Open a file for reading and writing. The file pointer will be placed at the beginning of the file. |
rb+ |
|
Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. Usually used for non-text files such as pictures. |
w |
|
Open a file for writing only. If the file already exists, open it and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. |
wb |
|
Open a file in binary format for writing only. If the file already exists, open it and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. Usually used for non-text files such as pictures. |
w+ |
|
Open a file for reading and writing. If the file already exists, open it and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. |
wb+ |
|
Open a file in binary format for reading and writing. If the file already exists, open it and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file. Usually used for non-text files such as pictures. |
a |
|
Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. That is to say, the new content will be written after the existing content. If the file does not exist, create a new file for writing. |
ab |
|
Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. That is to say, the new content will be written after the existing content. If the file does not exist, create a new file for writing. |
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. File opens in additional mode. If the file does not exist, create a new file for reading and writing. |
ab+ |
|
Open a file in binary format for appending. 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) a or ab:
def test4(): # a or ab For file appending, add new content after existing content f = open("day008/day_008_txt1", mode='a', encoding="utf-8") f.write("'<The Three-Character Classic:'Mother Ximeng, Choose Neighborhood'") f.flush() f.close() def test5(): # w + Writing and Reading (Not often used) Direct coverage f = open("day008/day_008_txt1", mode='w+', encoding="utf-8") f.write("ah") f.flush() f.close() def test6(): # a+ Additional reading # a+ Write before read and write after read are not able to get content, not cover. f = open("day008/day_008_txt1", mode='a+', encoding="utf-8") f.write("Learning and Learning") print(f.read()) f.flush() f.close()
1.3 OS operation file
File modification: read the contents of the old file into memory; modify; delete the old file; replace the old file name with the new file name
Disadvantage: Memory overflows easily. Solution: read line by line, change line by line
for line in file
Exercises1 import os 2 #Method 1 3 def test10(): 4 #Open the file and create a new file 5 with open("day008/day_008_1.txt",mode='r',encoding='utf-8') as f1,\ 6 open("day008/day_008_1_new.txt",mode='w',encoding='utf-8') as f2: 7 8 content = f1.read() 9 new_content = content.replace('Flying generals','Li Guang') # replace content 10 f2.write(new_content) # write to f2 in 11 os.remove('day008/day_008_1.txt') #delete original file 12 os.rename('day008/day_008_1_new.txt','A life without a marquis.txt') # 13 14 # Method 2 15 def test11(): 16 f1 = open("day008/day_008_1.txt", mode='r', encoding='utf-8') 17 f2 = open("day008/day_008_1_new.txt", mode='w', encoding='utf-8') 18 for line in f1: #One line, one line, one line 19 new_line = line.replace('Li Guang','Flying generals') 20 f2.write(new_line) 21 os.remove('day008/day_008_1.txt') 22 os.rename('day008/day_008_1_new','Li Guang's Characteristic Shou') 23 f2.flush()