码迷,mamicode.com
首页 > 其他好文 > 详细

文件读写

时间:2018-01-23 18:27:38      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:返回   分割线   模式   span   strip()   you   截断   enter   data   

1.
f=open(‘wuenda.txt‘,‘a‘,encoding=‘utf-8‘) #文件句柄 a:追加 w:覆盖写,r:读
f.write(‘when I was young\n I listen to the radio\n他们搬去哪了?\n‘)

#读:在r模式下
2.
f=open(‘wuenda.txt‘,‘r‘,encoding=‘utf-8‘) #文件句柄 a:追加 w:覆盖写,r:读
data = f.read()  #全部读入内存
print(data)
f.close()

3.
f = open(‘wuenda.txt‘,‘r‘,encoding=‘utf-8‘)
# 一行一行地读,内存中始终只有一行
count = 1
for line in f:
if count==9:
print(‘我是分割线‘.center(20,‘-‘))
else:
print(line.strip())
count+=1
f.close()

4.
f = open(‘wuenda.txt‘,‘r‘,encoding=‘utf-8‘)
print(f.tell()) #显示光标初始位置,按字符计数
print(f.readline().strip())
print(f.tell())
f.seek(10) #将光标移动至第10个字符
print(f.readline())

print(f.encoding) #显示编码方式
print(f.fileno()) #返回文件的内存编号
print(f.seekable()) #tty类型的文件:false
#通常情况下, 内存中的数据,先放在缓存中,缓存满了后,才写回硬盘
#flush可以不必等缓存满,随时写回

import sys,time
for i in range(20):
sys.stdout.write(‘#‘)
sys.stdout.flush()
time.sleep(0.2)
f1=open(‘wuenda.txt‘,‘a‘,encoding=‘utf-8‘)
f1.seek(96)
f1.truncate() #截断光标后面的内容

f=open(‘wuenda.txt‘,‘r+‘,encoding=‘utf-8‘)   #读写模式,最常使用
print(f.readline())
print(f.readline())
print(f.readline())
f.write(‘today is Jan 23th‘) #写到最后
print(f.readline())
f.close()

f=open(‘hello‘,‘wb‘)   #二进制写模式(网络传输)
f.write(‘hello python‘.encode())
f.close()

#文件内容修改(生成一个新的文件,使新文件中相应的str发生改变(替换))
f=open("wuenda.txt",‘r‘,encoding=‘utf-8‘)
f_new =open(‘test.txt‘,‘w‘,encoding=‘utf-8‘)
for line in f:
if "23th" in line:
line=line.replace("23th",‘24th‘,2)
f_new.write(line)
f.close()
f_new.close()

文件读写

标签:返回   分割线   模式   span   strip()   you   截断   enter   data   

原文地址:https://www.cnblogs.com/ceceliahappycoding/p/8336864.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!