本文实例讲述了python3.5文件修改操作。分享给大家供大家参考,具体如下:
1、文件修改的两种方式
(1)像vim一样将文件加载到内存中,修改完之后再写回源文件。
(2)打开文件,修改后写入到一个新的文件中。
注:这里操作的txt文本文件可参考前面一篇 python3.5文件读与写操作
1
2
3
4
5
6
7
8
9
10
11
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:zhengzhengliu
f = open ( "song" , 'r' ,encoding = "utf-8" )
f_new = open ( "song2.txt" , 'w' ,encoding = "utf-8" ) #打开一个新文件(往里面写内容)
for line in f:
if "其实爱我真的很简单" in line:
line = line.replace( "其实爱我真的很简单" , "其实爱你真的很简单" )
f_new.write(line)
f.close()
f_new.close()
|
运行结果:
2、with语句:为了避免打开文件之后忘记关闭,可以通过with语句管理上下文。
1
2
3
4
|
#为了避免打开文件后忘记关闭,可以通过with语句管理上下文
with open ( "song" , 'r' ,encoding = "utf-8" ) as f:
for line in f:
print (line)
|
通过with语句,同时打印多个文件
1
2
3
4
5
|
#打开多个文件
with open ( "song" , 'r' ,encoding = "utf-8" ) as f,\
open ( "song2" , 'r' ,encoding = "utf-8" ) as f2:
for line in f:
print (line)
|
希望本文所述对大家python程序设计有所帮助。
原文链接:https://blog.csdn.net/loveliuzz/article/details/77778680