目录
文件创建、打开:open()
打开/创建文件,模式可选。
filename = "test.txt"
open(filename,'w')#以写入的方式打开filename
#因为在打开文件后操作完还需要关闭文件释放占用的资源,
#除了手动使用close之外,
#还可使用with open(filename,'r') as file 打开/创建文件进行操作,其可以自动执行关闭文件的功能。
#手动close
filename = "test.txt"
my_file = open(filename,'w')
my_file.close()
#自动close
with open('example.txt', 'r') as file:
content = file.read()
print(content)
模式 | 用途 | + | b | b+ |
r | 只读,指针位于文件开头。文件不存在会引发错误。 | r+ 读写 | rb 以二进制格式打开 | rb+ 以二进制格式打开文件,用于读写。 |
w | 写入,若文件存在会清空文件从开头写,不存在则创建。 | w+ 读写 | wb 以二进制格式打开 | wb+ 以二进制格式打开文件,用于读写。 |
a | 打开,追加内容。文件存在则指针位于文件结尾,在已有内容的基础上追加新内容,若不存在则创建文件 | a+ 读写 | ab 以二进制格式打开 | ab+ 以二进制格式打开文件,用于读写。 |
注:如果后续想要执行写入操作,可以使用".truncate(数字)"指定写入位置,数字的单位为字节,默认从最后开始写入。
文件读取:read() 和readline()
函数 | read() | readline() |
功能 | 一次性读取整个文件的内容,并返回一个字符串。 | 每次调用readline() 函数会读取文件中的一行,并返回一个字符串。可以通过循环调用readline() 函数来逐行读取文件内容,直到读取到文件末尾。 |
适用场景 |
|
|
使用示例:
#假设'example.txt'文件内容如下:
#Hello \n
#World
#read()
with open('example.txt', 'r') as file:
content = file.read()
print(content)
#输出:Hello \n
# World
#readline()
with open('example.txt', 'r') as file:
line = file.readline()
while line:
print(line.strip()) # 使用strip()函数去除换行符
line = file.readline()
#输出:Hello
# World
文件写入:write()
使用示例:
content = "Hello, world!"
with open('output.txt', 'w') as file:
file.write(content)#向file写入content