python 文件操作

f=open('test.txt','w',encoding='utf8')
f.write('hello\n')
f.close()
f=open('test.txt','a')
f.write('2hello')
f.close()
f=open('test.txt','r')
print(f.read(1))
print(f.readline())#读到回车,再加上print的回车,一共两个回车
print(f.read())#由于读光标的原因,它不会重头再read
f.close()
h
ello

2hello
f=open('test.txt','r',encoding='utf-8')
for i in f.readlines():#f.readlines一行一行读取的集合
    print(i.strip())#去掉每行的回车,否则会与print自带的回车重复,换两行
f.close()

 以上方法不常用

 

f=open('1.txt','r',encoding='utf8')
for i in f:
    print(i.strip())  #常用
f.close()

 

f=open('1.txt','r',encoding='utf8')
print(f.tell())#找光标的位置
print(f.read(2))#一个中文占三个字符,光标的位置走6
print(f.tell())
f.seek(3)#将光标移到第一个中文后,写不是3的倍数读取中文时会报错
print(f.read(3))
f.close()
0
君不
6
不见,

 报错:

 flush的作用:

import sys,time
#下面会一次性出现30个*,因为是写在缓冲区的,写好后一次性显示出来
for i in range(30):
    sys.stdout.write("*")
    time.sleep(0.2)
#下面类似进度条的效果,因为flush能将缓冲区的东西马上显示出来
for i in range(30):
    sys.stdout.write("*")
    sys.stdout.flush()
    time.sleep(0.2)
#以上sys.stdout可以使用print('*',end='',flush='True')替换

 truncate截断方法:

f=open('1.txt','w',encoding='utf8')
f.write('helloworld')
f.truncate(5)#只保留前5个,截断,文件中显示hello
f.close()

 文件模式:

r+:读写模式,读正常,写的时候在最后写,但写了之后光标移动到最后,想要再读需要移动光标

w+:写读模式,写在最开始写,会覆盖原来的内容,想要读的时候要移动光标,基本上不用

a+:光标一开始在最后,读写都是在最后,不会覆盖

文件拷贝以及修改:

number=0
f1=open('1.txt','r',encoding='utf8')
f2=open('2.txt','w',encoding='utf8')
for line in f1:
    number+=1
    if number==2:
        f2.write(''.join([line.strip(),' I like this sentence\n']))
    else:
        f2.write(line)
f1.close()
f2.close()

 以下代码能实现同样功能:(用 with 同时管理多个文件对象,with a as b 相当于 b=a)

with open('1.txt','r',encoding='utf8') as f1,open('2.txt','w',encoding='utf8')as f2:
    for line in f1.readlines():
        f2.write(line)

 

posted @ 2019-07-30 16:09  淇实是我  阅读(128)  评论(0编辑  收藏  举报