Python file reading and writing is divided into three steps
Open a file, get a handle, manipulate a file, close a file
The basic operation of the file is as follows:
1 f = open ("e:\\person_practice\\python\\test.txt","R" # Open File 2 fr = F.read () # Read file 3 Print(FR)
File open, you need to specify the file path, open mode, Windows file path if it is "E:\person_practice\python\test.txt", you need to transfer "\" or change to:
"E:/person_practice/python/test.txt"
Open mode is divided into R, W, a three ways, "+" means you can read and write at the same time
R read-only, default mode
W write-only, unreadable, create if file does not exist, delete content if present, write new content
A append, unreadable, create if the file does not exist, append new content if it exists
R+ can be read, writable, append, if the file does not exist, then the error
w+ readable and writable, if the file exists, the content will be emptied, and the newly written content can be read
A + readable, writable, can be appended, if the file exists, append new content, read the default pointer at the end of the file, if you need to read the entire file, the pointer must be zero "f.seek (0)"
To open the file in this way, you need to close the file immediately after use, you can use the "with" method to resolve:
With open ("f:\\python_scripts\\py\\test.txt","R"
for inch fr:
Print (line)
This method automatically closes the file after you have finished using it.
Common file Operations Commands
Fr.read () # reads all content fr.readline () # reads a line fr.readlines () # reads all file contents, returns a list # the above three commands are used with caution in large files, which reads the contents into memory and consumes large memory . Fr.seek (0) # Current file pointer position in 0-bit fr.writelines (["a", " b "]) # write a list to a file
File modification
There are two ways to modify a file, one is to read the contents of the file into memory, empty and rewrite it, and the second is to write the contents of the modified file into a new file;
The first way
1With open ("F:\\python_scripts\\py\\test.txt","r+") as FR:#Open in a read way2res = Fr.read ()#read file to memory3New_res = Res.replace ("Learning","study")#Modify File Contents4Fr.write (New_res)#modified content rewritten into a file5 Print(New_res)
The second way
With open ("Test_1.txt","R") as FR, open ("Test_2.txt","w+") as FW:#open multiple files at the same time forLineinchFr#iterate through each lineNew_line = Line.replace ("1","a")#Change 1 to aFw_new = Fw.write (new_line)#write the modified content in the FW
For reference, see: http://www.nnzhp.cn/blog/2016/12/19/python%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%E4%B8%89%E6%96%87%E4%BB% b6%e6%93%8d%e4%bd%9c%e5%92%8c%e9%9b%86%e5%90%88/
python--file read/write