重学文件操作

1.读取之后在第五行末尾添加内容

with open('满江红.txt', 'r', encoding='utf8') as f:
nub = 0
for i in f:
nub += 1
if nub == 5:
i = ''.join([i.strip(), 'i like it.'.title()])
print(i.strip())

2.修改文件内容,并储存

filedate = ''
with open('满江红.txt', 'r+', encoding='utf8') as f:
    for i in f:
        if '山如削' in i:
            i = i.replace('山如削', 'I hate it.')  # 符合条件替换内容
        filedate += i  # 将所有内容写入临时文件
with open('满江红.txt', 'w', encoding='utf8') as f:
    f.write(filedate)  # 清空原文件并将filedate作为内容重新写入

 

posted @ 2018-01-31 10:05  xusuns  阅读(141)  评论(0编辑  收藏  举报