1. Open File
F=open (' a.txt ', ' A + ', encoding= ' utf-8 ') #f代表的是文件对象, called a handle
F.seek (0) Put the file pointer to the front
There are 3 types of File open modes:
1:w write mode, it is unreadable, when using W it will empty the original content and then write
w+ write mode, when using W, it will empty the original content and then write
2:R read mode, can only read and cannot write, and the file must exist
r+ read-write mode, the original file still exists, but if the file does not exist will be an error
3:A Append mode, write only, add content at the end of the file
A + can read and write, the default file pointer in the last
4:rb+, wb+,ab+, this is binary mode open or read, some music files, pictures and so on
F=open (' a.txt ') #如果在打开的文件的时候, do not specify mode, that is, read mode
The file object is also iterative, read-only 1 lines of content, this high efficiency
For line in F: #f代表文件对象
Print (line) #打印每行内容
#直接循环文件对象的话, looping through the contents of each line of the file
2. Read the contents of the file
Print (F.read ()) #读文件全部内容, returns a string
Print (F.readlines ()) #读文件全部内容, returns a list
Print (F.readline ()) #读文件一行内容, can read only one line at a time
3. Writing content
F.write (' hhh ') #写文件, writing a string
F.writelines ([' 123 ', ' 345 ', ' 567 ']) #可以把列表写入文件
4. File modification
# res = F.read () #打开文件
# f.seek (0) #指针
# f.truncate () #清空文件内容
# new_res = Res.replace (' Nihao ', ' Nibuhao ') #把nibuhao replace Nihao
# f.write (new_res) Read new content
#以上方法, reading for large files is not available
important: each line reads and puts a new file:
import os
f=open (' a.txt ', ' A + ', encoding= ' utf-8 ') #打开文件
# fw = open (' A.txt.new ', ' W ', encoding= ' utf-8 ') #把替换好的文件放入到fw文件中
# for line in F:
# new_res = line.replace (' Learn ', ' don't Learn ')
# fw.write (new_res)
# F.close () # Close F file
# fw.close () #关闭fw文件
# Os.remove (' a.txt ') #删除文件
# os.rename (' a.txt.new ', ' a.txt ') #重命名把a. txt.new Rename to A.txt
5.flush usage, with usage
#flush用法
Import time
FW = open (' Python.txt ', ' W ', encoding= ' utf-8 ')
Fw.write (' No class next week! ‘)
Fw.flush () #写完之后立马生效
Exit (' Goodbye ')
Time.sleep (#程序休息30秒)
Fw.close ()
#with的用法, when your file is no longer in use, it will automatically close the file to you
# with open (' Python.txt ', encoding= ' Utf-8 ') as fr:
# Print (Fr.read ())
Python note 13-file read and write