代码改变世界

python操作文件

2017-12-11 20:41  龙武大帝  阅读(213)  评论(0编辑  收藏  举报

1、只读r

f = open("info",'r',encoding="utf-8")
f.write("hello")

Traceback (most recent call last):
  File "/Users/chuck/Desktop/OneOaaS/python/s17/day3/file_test.py", line 8, in <module>
    f.write("hello")
io.UnsupportedOperation: not writable

2、只写w(不可读;不存在则创建;存在则删除内容;)

f = open("info",'w',encoding="utf-8")
print(f.read())

Traceback (most recent call last):
  File "/Users/chuck/Desktop/OneOaaS/python/s17/day3/file_test.py", line 7, in <module>
    print(f.read())
io.UnsupportedOperation: not readable

3、追加模式a(不可读;不存在则创建;存在则只追加内容;)

f = open("info",'a',encoding="utf-8")

print(f.read())
f.write('chuck')

Traceback (most recent call last):
  File "/Users/chuck/Desktop/OneOaaS/python/s17/day3/file_test.py", line 9, in <module>
    print(f.read())
io.UnsupportedOperation: not readable

4、可读可写模式r+,但是写只能是追加模式

5、先写后读w+,但是先写的话,如果文件存在,在清空,然后写进去

6、可以追加读写a+, 写也是追加

7、rb/wb/ab  读写和追加二进制文件,不是二进制也能读,但是会显示二进制形式

8、其他操作

f.tell()    #当前文件读取的位置,即当前读取了多少个字符
f.seek()    #当前的光标位置
f.truncate(10) #截取前10个数字

9、文件修改

f = open("info",'r',encoding="utf-8")
f1 = open("info_bak",'w',encoding="utf-8")

for line in f:
    if "what's happened" in line:
        line = line.replace("what's happened","chuck is good")
    f1.write(line)
f.close()
f1.close()

10、with......as

with open("info",'r') as f:    #打开一个文件
    for line in f:
        print(line)

with open("info") as f,\
        open("info1") as f1:    #同时打开多个文件
    for line in f:
        print(line)