1、写文件
# mode
# 'r' open for reading (default)
# 'w' open for writing, truncating the file first
# 'x' create a new file and open it for writing
# 'a' open for writing, appending to the end of the file if it exists
# 'b' binary mode
# 't' text mode (default)
# '+' open a disk file for updating (reading and writing)
# 'U' universal newline mode (deprecated)
file = open("test.txt", mode='w')
file.write("test" + "\n")
file.write("Hello World" + "\n")
file.close()
# 追加
file = open("test.txt", mode='a')
file.write("test" + "\n")
file.write("Hello World" + "\n")
file.close()
2、读文件
# 读文件
file = open("test.txt", mode='r', encoding="utf-8")
# 读取所有信息
s1 = file.read()
# 指定读取字符数
s2 = file.read(1)
# 读取一行
s3 = file.readline()
# 读取多行
s4 = file.readlines()
print(s1 + "--------------")
print(s2 + "--------------")
print(s3 + "--------------")
print(s4)
file.close()