Python实现修改文件内容的方法分析


Posted in Python onMarch 25, 2018

本文实例讲述了Python实现修改文件内容的方法。分享给大家供大家参考,具体如下:

1 替换文件中的一行

1.1 修改原文件

① 要把文件中的一行Server=192.168.22.22中的IP地址替换掉,因此把整行替换。

data = ''
with open('zhai.conf', 'r+') as f:
  for line in f.readlines():
    if(line.find('Server') == 0):
      line = 'Server=%s' % ('192.168.1.1',) + '\n'
    data += line
with open('zhai.conf', 'r+') as f:
  f.writelines(data)

② 把原文件的hello替换成world。

#!/usr/local/bin/python
#coding:gbk
import re
old_file='/tmp/test'
fopen=open(old_file,'r')
w_str=""
for line in fopen:
  if re.search('hello',line):
    line=re.sub('hello','world',line)
    w_str+=line
  else:
    w_str+=line
print w_str
wopen=open(old_file,'w')
wopen.write(w_str)
fopen.close()
wopen.close()

1.2 临时文件来存储数据

实现如下功能:将文件中的指定子串 修改为 另外的子串

python 字符串替换可以用2种方法实现:

①是用字符串本身的方法。str.replace方法。
②用正则来替换字符串: re

方法1:

#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import sys,os
if len(sys.argv)<4 or len(sys.argv)>5:
  sys.exit('There needs four or five parameters')
elif len(sys.argv)==4:
  print 'usage:./file_replace.py old_text new_text filename'
else:
  print 'usage:./file_replace.py old_text new_text filename --bak'
old_text,new_text=sys.argv[1],sys.argv[2]
file_name=sys.argv[3]
f=file(file_name,'rb')
new_file=file('.%s.bak' % file_name,'wb')#文件名以.开头的文件是隐藏文件
for line in f.xreadlines():#f.xreadlines()返回一个文件迭代器,每次只从文件(硬盘)中读一行
  new_file.write(line.replace(old_text,new_text))
f.close()
new_file.close()
if '--bak' in sys.argv: #'--bak'表示要求对原文件备份
  os.rename(file_name,'%s.bak' % file_name)  #unchanged
  os.rename('.%s.bak' % file_name,file_name)  #changed
else:
  os.rename(file_name,'wahaha.txt')#此处也可以将原文件删除,以便下一语句能够正常执行
  os.rename('.%s.bak' % file_name,file_name)

方法2:

open('file2', 'w').write(re.sub(r'world', 'python', open('file1').read()))

2 使用sed

2.1 sed命令:

sed -i "/^Server/ c\Server=192.168.0.1" zhai.conf  #-i表示在原文修改
sed -ibak "/^Server/c\Server=192.168.0.1" zhai.conf  #会生成备份文件zhai.confbak

2.2 python调用shell的方法

os.system(command)

在一个子shell中运行command命令,并返回command命令执行完毕后的退出状态。这实际上是使用C标准库函数system()实现的。这个函数在执行command命令时需要重新打开一个终端,并且无法保存command命令的执行结果。

os.popen(command,mode)

打开一个与command进程之间的管道。这个函数的返回值是一个文件对象,可以读或者写(由mode决定,mode默认是'r')。如果mode为'r',可以使用此函数的返回值调用read()来获取command命令的执行结果。

commands.getstatusoutput(command)

使用os. getstatusoutput ()函数执行command命令并返回一个元组(status,output),分别表示command命令执行的返回状态和执行结果。对command的执行实际上是按照{command;} 2>&1的方式,所以output中包含控制台输出信息或者错误信息。output中不包含尾部的换行符。

subprocess.call(["some_command","some_argument","another_argument_or_path"])
subprocess.call(command,shell=True)**

subprocess.Popen(command, shell=True)

如果command不是一个可执行文件,shell=True不可省。

使用subprocess模块可以创建新的进程,可以与新建进程的输入/输出/错误管道连通,并可以获得新建进程执行的返回状态。使用subprocess模块的目的是替代os.system()、os.popen*()、commands.*等旧的函数或模块。

最简单的方法是使用class subprocess.Popen(command,shell=True)。Popen类有Popen.stdinPopen.stdoutPopen.stderr三个有用的属性,可以实现与子进程的通信。

将调用shell的结果赋值给python变量

代码如下:

handle = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
print handle.communicate()[0]

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python urllib模块urlopen()与urlretrieve()详解
Nov 01 Python
Python实现抓取网页并且解析的实例
Sep 20 Python
Python实现批量下载文件
May 17 Python
Python 递归函数详解及实例
Dec 27 Python
PyCharm 常用快捷键和设置方法
Dec 20 Python
python3.5 tkinter实现页面跳转
Jan 30 Python
python 返回列表中某个值的索引方法
Nov 07 Python
python遍历小写英文字母的方法
Jan 02 Python
详解python的四种内置数据结构
Mar 19 Python
Python读取文件内容为字符串的方法(多种方法详解)
Mar 04 Python
使用Django xadmin 实现修改时间选择器为不可输入状态
Mar 30 Python
详解如何修改jupyter notebook的默认目录和默认浏览器
Jan 24 Python
利用python为运维人员写一个监控脚本
Mar 25 #Python
python实现数据写入excel表格
Mar 25 #Python
使用requests库制作Python爬虫
Mar 25 #Python
利用Python代码实现数据可视化的5种方法详解
Mar 25 #Python
Python cookbook(数据结构与算法)同时对数据做转换和换算处理操作示例
Mar 23 #Python
教你使用python实现微信每天给女朋友说晚安
Mar 23 #Python
python微信公众号开发简单流程
Mar 23 #Python
You might like
PHP定时任务获取微信access_token的方法
2016/10/10 PHP
php file_get_contents取文件中数组元素的方法
2017/04/01 PHP
老生常谈PHP面向对象之命令模式(必看篇)
2017/05/24 PHP
PHP中使用CURL发送get/post请求上传图片批处理功能
2018/10/15 PHP
Array.prototype.slice 使用扩展
2010/06/09 Javascript
js综合应用实例简单的表格统计
2013/09/03 Javascript
JS中判断JSON数据是否存在某字段的方法
2014/03/07 Javascript
用js模拟struts2的多action调用示例
2014/05/19 Javascript
Validform+layer实现漂亮的表单验证特效
2016/01/17 Javascript
JavaScript中的Reflect对象详解(ES6新特性)
2016/07/22 Javascript
超详细的JS弹出窗口代码大全
2020/04/18 Javascript
微信小程序canvas写字板效果及实例
2017/06/15 Javascript
vue底部加载更多的实例代码
2018/06/29 Javascript
浅谈Fetch 数据交互方式
2018/12/20 Javascript
Vue编程式跳转的实例代码详解
2019/07/10 Javascript
JavaScript中的连续赋值问题实例分析
2019/07/12 Javascript
IntelliJ IDEA编辑器配置vue高亮显示
2019/09/26 Javascript
js实现数字滚动特效
2019/12/16 Javascript
ES6函数实现排它两种写法解析
2020/05/13 Javascript
利用 Monkey 命令操作屏幕快速滑动
2016/12/07 Python
python中 chr unichr ord函数的实例详解
2017/08/06 Python
TensorFlow实现创建分类器
2018/02/06 Python
selenium+python实现1688网站验证码图片的截取功能
2018/08/14 Python
对pandas将dataframe中某列按照条件赋值的实例讲解
2018/11/29 Python
一篇文章搞懂Python的类与对象名称空间
2018/12/10 Python
对Python3之方法的覆盖与super函数详解
2019/06/26 Python
python requests指定出口ip的例子
2019/07/25 Python
Python类如何定义私有变量
2020/02/03 Python
matplotlib绘制多子图共享鼠标光标的方法示例
2021/01/08 Python
CSS3 选择器 属性选择器介绍
2012/01/21 HTML / CSS
Marc Jacobs彩妆官网:Marc Jacobs Beauty
2017/07/03 全球购物
英国家庭和商业健身器材购物网站:Fitness Options
2018/07/05 全球购物
大专生工程监理求职信
2013/10/04 职场文书
单位领导证婚词
2014/01/14 职场文书
无刑事犯罪记录证明范本
2014/09/29 职场文书
无婚姻登记记录证明
2015/06/18 职场文书