舉個(gè)例子,我們需要從file1.txt讀取文本中的數(shù)據(jù)粹舵,
在每一行結(jié)尾處属百,寫入當(dāng)前時(shí)間茬末,
并將修改后的文本寫入文件?file3.txt
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time;
asctime = time.asctime( time.localtime(time.time()) )
# 打開文件
flog = open("file1.txt", "a+")
fdes = open("file3.txt", "a+")
#把文件指針從末尾移到開頭
flog.seek(0,0)
#讀取全部數(shù)據(jù)
print "全文:"+flog.read()
flog.seek(0,0)
#讀每行
list_of_all_the_lines = flog.readlines()
#如果文件是文本文件银亲,還可以直接遍歷文件對(duì)象獲取每行:
for line in list_of_all_the_lines:
? ? ?print line
? ? ?#刪除換行符
? ? ?line=line.strip('\n')
? ? ?#寫入數(shù)據(jù)
? ? ?fdes.write (line+" "+asctime+'\n')
#把文件指針從末尾移到開頭
fdes.seek(0,0)
#讀取全部數(shù)據(jù)
print "fdes全文:"+fdes.read()
# 關(guān)閉文件
flog.close()
fdes.close()