Python修改文件方法——字符串替换

#字符串替换import sysf = open("yesterday2","r",encoding="utf-8")f_new = open("yesterday2.bak","w",encoding="utf-8")

find_str = sys.argv[1]replace_str = sys.argv[2]for line in f:    if find_str in line:        line = line.replace(find_str,replace_str)    f_new.write(line)f.close()f_new.close()

#with执行问了,文件就自动关闭了! 开发规范一行代码不能超过80字符: \
with open("yesterday2","r",encoding="utf-8") as f ,\         open("yesterday2", "r", encoding="utf-8") as f2:    for line in f:        print(line)

原文地址:https://www.cnblogs.com/wzsx/p/8969775.html

时间: 2024-07-30 02:48:04

Python修改文件方法——字符串替换的相关文章

python 修改文件内容

python 修改文件内容 一.修改原文件方式 1 def alter(file,old_str,new_str): 2 """ 3 替换文件中的字符串 4 :param file:文件名 5 :param old_str:就字符串 6 :param new_str:新字符串 7 :return: 8 """ 9 file_data = "" 10 with open(file, "r", encoding

python打开文件查询字符串时报UnicodeDecodeError: 'gbk' codec can't decode byte 0xaa in position 19: illegal multibyte sequence错误

当这样打开时报错了 lines = open(path).readlines() open(path).close() for line in lines: idx1 = line.find('检测到的 SN 为:') idx1 += len('检测到的 SN 为:') idx2 = line.find(' 或许与您申请的SN不符,请联系技术提供方',idx1) responsetimestr = line[idx1:idx2] rts = responsetimestr   UnicodeDe

[Python]读写文件方法

http://www.cnblogs.com/lovebread/archive/2009/12/24/1631108.html [Python]读写文件方法 http://www.cnblogs.com/xuxn/archive/2011/07/27/read-a-file-with-python.html Python按行读文件 1. 最基本的读文件方法: # File: readline-example-1.py file = open("sample.txt") while 1

修改文件名称或者替换文件名中的内容

import os def putName(path, flag, oldName, newName): """ 修改文件名称或者替换文件名中的内容 """ dirList = os.listdir(path) for i in dirList: if i.startswith('.'): continue newPath = os.path.join(path, i) if os.path.isdir(newPath): putName(new

python文件操作--字符串替换

如把test.txt文件的 所有 AAA 字符串 替换成 aaaaa 1 with open('test.txt','+r') as f: 2 t = f.read() 3 t = d.replace('AAA', 'aaaaaa') 4 #读写偏移位置移到最开始处 5 f.seek(0, 0) 6 f.write(t)

PYTHON之批量文件指定字符串替换

在工作应用中,运维自动化的基础是标准化. 而标准化的工作,是难点,在公司相关部门的配合. 那么,在有标准化之后,相应的部署脚本,就比较好写了. 贡献一个在类似环境下可以运用的东东.. 当然,可以写得更好点,只是时间不够.. #!/usr/bin/python # -*- coding:utf-8 -*- import sys,os #定义需要替换IP的所有文件列表,运用环境下一定要弄清楚,要不然会导致不能正常运行.如果所有环境都定义好,则此脚本通用性更强 repip_file_list = ["

python 修改文件中的内容

在python的文件操作中,是没有办法对文件中具体某行或者某个位置的内容进行局部的修改的,如果需要对文件的某一行内容进行修改,可以先将文件中的所有的内容全部读取出来,再进行内容判断,是否是需要修改的内容,如果是就替换内容,并且将修改替换过的内容和没有修改的内容全部写入到新的文件中. # 打开旧文件 f = open('file_text.txt','r',encoding='utf-8') # 打开新文件 f_new = open('file_text_bak.txt','w',encoding

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 修改文件内容的程序

#1.修改文件的内容 #运行的时候要 python xxx.py hh.txt hehe hahaimport sys,osinputs = sys.argv#存的是所有运行时候传进来的参数#它就是用来获取在用python命令运行python文件的时候,传入的参数#1.判断用户输入的是不是够个数if len(inputs)<4: print('参数不够,至少需要3个参数,e.g: python xx.py xx.txt old_str new_str..')else: file_name = i