前言
文件操作
打开文件–>进行操作–>关闭文件
r:(默认)
只能读,不能写
读取的文件不存在,会报错
FileNotFoundError: [Errno 2] No such file or directory:
r+:
可以执行读写操作
文件不存在,报错
默认情况下,从文件指针所在位置开始写入
w:
write only
会清空文件之前的内容
文件不存在,不会报错,会创建新的文件并写入
w+:
rw
会清空文件内容
文件不存在,不报错,会创建新的文件
a:
write only
不会清空文件内容
文件不存在,会报错
a+:
rw
文件不存在,不报错
不会清空文件内容
举例
f = open('/tmp/passwd','r+')
content = f.read()
print(content)
f.write('hello') ##插入位置在文件尾部
print(content)
print(f.readable())
print(f.writable())
f.close()
运行结果:
:0:0:root:/root:/bin/bash
:0:0:root:/root:/bin/bash
True
True
f = open('/tmp/passwd','r+')
f.write('python') ##插入位置在文件头部
content = f.read()
print(content)
print(f.tell())
print(f.read())
print(f.tell())
f.close()
运行结果&#