Python对指定文件内容进行全局替换


关于对指定文件内容进行全局替换的Python实现具体解释都附在代码里了
代码如下:

import os
import sys
cs = sys.argv
old_cs = cs[1]     # 将要替换掉的值赋给old_cs
new_cs = cs[2]      # 将要替换成的值赋给new_cs
filename = cs[3]    # 将操作的文件名赋给filename
new_file = filename + "_new"
if len(cs) != 4:
    print('check it carefully and try it again!')
    os._exit(0)
else:
    print('------   replacing...   ------')
count = 0
with open(filename, mode='r', encoding='utf-8') as f:
    data1 = f.read()
    if old_cs in data1:
        data1 = data1.split('\n')  # 将i分行切片
        file_new = open(new_file, mode='w', encoding='utf-8')

        for i in data1:
            if old_cs in i:    # 判断各行中是否存在old_cs
                i = i.replace(old_cs, new_cs)
                file_new.write(i + '\n')
                count += 1
        file_new.close()
if count > 0:
    if os.path.exists(filename):        # 判断路径中是否存在名为filename的文件
        os.remove(filename)             # 删除该文件
        os.replace(new_file, filename)  # 用filename给new_file重命名
        print('replace successfully {} times'.format(count))
else:
    print('{0} is not in {1}...'.format(old_cs, filename))

操作文件data数据如下:

小明 男 178 71
小强 男 188 77
小梦 女 168 61
小艺 女 165 55
小妮 女 161 57
小萱 女 171 46
小页 男 183 67

运行代码及结果如下:

H:\Python\anzhuangbao\helloworld>python changefile.py 72 48 data
------ replacing... ------
replace successfully 2 times

H:\Python\anzhuangbao\helloworld>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM