python_36_文件操作4

f=open('test.txt','a',encoding='utf-8')
#f.truncate()#截断,不指定将清空所有内容
f.truncate(5)#从头开始截断,截断5个字符  注:使用f.seek()改变光标位置不顶用
f.close()

f=open('yesterday','r+',encoding='utf-8')#读写文件
print(f.readline())
print(f.readline())
print(f.readline())#打印第三行
f.write("----------------没办法,没有写在第三行,与光标位置无关,只能写在最后----------------")
print(f.readline())#照常打印第四行\
f.close()

f=open('yyy','w+',encoding='utf-8')#写读:创建一个文件再往里边写    其实没啥用
print(f.readline())#读不到东西
print(f.readline())#读不到东西
print(f.readline())#读不到东西
f.write("----------------写到文件中了----------------")
f.close()
#1 yyy文件中原始内容
# YESTERDAY ONCE MORE
# 2 When I was young I'd listen to the radio 当年少时,我爱听收音机
# 3 Waiting for my favorite songs 等待我最喜爱的歌
# 4 When they played I'd sing along, 当播放后,我喜欢一个人唱
# 5 It make me smile 这让我开心的笑了
# 6 Those were such happy times 像这样快乐的日子
# 7 and not so long ago 没有多久
# 8 How I wondered where they'd gone. 我想知道他们去了哪里
# 9 But they're back again 但他们再次回来
# 10 just like a long lost friend 像失去很久的朋友
# 11 All the songs I love so well 所有的歌,我是这么的喜欢
# 12 Every shalala shalala
# 13 every wo'wo wo'wo
# 14 still shines. 依然闪亮
# 15 Every shing-a-ling-a-ling shing-a-ling-a-ling


f = open('yesterday','a+',encoding='utf-8')#a+同a
print(f.readline())#读不出来
f.close()
f=open('yesterday','rb')#二进制文件读,网络传输中使用
print(f.readline())
print(f.readline())
print(f.readline())
f.close()

f=open('zzz','wb')#二进制文件写
f.write('终于要学完这一章了'.encode())
f.close()

f = open('yesterday','rU',encoding='utf-8')#rU同r+U,可以将\r \n  \r\n自动转化成\n (目的使文件在Linux和Windows上通用)

  

posted @ 2018-01-13 20:33  耐烦不急  阅读(232)  评论(0编辑  收藏  举报