One, the file operation
Open () #打开文件
Open (' A.txt ', ' W ', encoding= ' utf-8 ') #防止乱码
R, a, w--read only, append write, write only three modes
u# change the line breaks in all the files to \ n
b# binary operation
The. Read () #读文件
. ReadLine () #读取一行, a row of read files
. ReadLines () #读文件的全部内容, the return is a list
For line in F:
Print (line) #循环读取文件每行内容, recommend this method
The. Write () #写
. Wrielines () #写一个list
. Seek (0) #指定文件指针位置
. Tell () #读文件
. Truncate () #清空
. Close () #关闭文件
. Flush () #缓冲区的文件立即生效
With open (' A.txt ', ' R ') as fw,\ #一行代码写不完可以加一个 \ Connects two lines of code; Use with to write no more. Close
Open (' B.txt ', ' W ', encoding= ' Utf-8 '):
Src_res=fw.read ()
Res=src_res.replace (' xxx ', ' DSSSD ') #替换
Fw.write (res) #如果要修改原文件, you must create a new file and write the modified contents of the original file into the new file.
Os.remove (' A.txt ')
Os.rename (' B.txt ', ' a.txt ') #把原文件删除, rename the new file to the original file
Python Basics Supplement