1.文件读取的三部曲:打开 ---> 操作 ----> 关闭
r(默认参数):
-只能读,不能写
-读取文件不存在 会报错
FileNotFoundError: [Errno 2] No such file or directory: ‘/tmp/westos‘
w(写)
-write only
-文件不存在的时候,会自动创建新的文件
-文件存在的时候,会清空文件内容并写入新的内容
a(追加):
-write only
-写:不会清空文件的内容,会在文件末尾追加
-写:文件不存在,不会报错,会创建新的文件并写入内容
r+
-r/w
-文件不存在,报错
-默认情况下,从文件指针所在位置开始写入
w+
-r/w
-文件不存在,不报错
-会清空文件内容
a+
-r/w
-文件不存在,不报错
-不会清空文件,在末尾追加
f = open(‘/tmp/westos3‘,‘w+‘) /tmp/westos3文件不存在,自动创建了文件并写入了信息
print(f)
print(f.tell()) 打印文件指针的位置 此时为0
f.write(‘111‘) 写入‘111’
print(f.tell()) 再次打印指针位置可以看到指针为3
f.close() 关闭文件
f = open(‘/tmp/redhat‘,‘a+‘) 不会清空文件,在末尾追加
print(f) 文件指针的位置开始为0
print(f.tell())
f.write(‘111‘) 文件执行5此后指针在15
print(f.tell())
f.close() 关闭文件
2.文件的操作
#1.打开文件
f = open(‘/tmp/westos‘,‘r‘)
#2.操作
print(f)
#读文件
#content = f.read()
#print(content)
#写文件
#告