6

python修改文件内容,不需要read,write多个动作。

 3 years ago
source link: https://blog.csdn.net/china_video_expert/article/details/39698525
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

python修改文件内容,不需要read,write多个动作。

python  要修改文件内容,常用 是先read,后write , 再 rename,很不爽。

比如:需要 把       yuv_dir ="../HD/"   # "H:/HD_Master/1080i25/"

                改为       yuv_dir ="C:/HD/"   # "H:/HD_Master/1080i25/"

很简单,但实际不好操作,因为read后文件指针就到后一行了,要使用seek到前一行等,很不好。

很多应用多需要处理文件,而处理文件有一个固定的模式:打开文件,读入一些数据,处理这些数据,打印到屏幕上或写入另一个文件。

那么,如果我们想修改之后立即写回文件,该怎么做呢?用什么模式打开?又怎么读写?

我个人尝试了很多中方法,不是无法实现,就是操作非常麻烦。最终放弃。

幸运的是,Python内置模块fileinput就可以轻松完成。代码如下:

for line  in fileinput.input("case_1_gaoqing.py",inplace=1):
    line = line.replace("..","C:")    
    print line,
这样就实现了需要的目的,很简单吧。

关于更多fileinput的资料,在这里http://docs.python.org/library/fileinput.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK