replace文件内容中的string
如何打开一个文件Stud.txt,然后用“Orange”replace“A”的出现?
with open("Stud.txt", "rt") as fin: with open("out.txt", "wt") as fout: for line in fin: fout.write(line.replace('A', 'Orange'))
如果你想replace同一个文件中的string,你可能必须把它的内容读入一个局部variables,closures它,然后重新打开它写入:
在这个例子中,我使用了with语句 ,它在with
块被终止之后closures了文件 – 通常是最后一个命令执行完成或者exception。
def inplace_change(filename, old_string, new_string): # Safely read the input filename using 'with' with open(filename) as f: s = f.read() if old_string not in s: print '"{old_string}" not found in {filename}.'.format(**locals()) return # Safely write the changed content, if found in the file with open(filename, 'w') as f: print 'Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()) s = s.replace(old_string, new_string) f.write(s)
值得一提的是,如果文件名不一样,我们可以用一个单独with
语句做得更加优雅。
就像是
file = open('Stud.txt') contents = file.read() replaced_contents = contents.replace('A', 'Orange') <do stuff with the result>
with open('Stud.txt','r') as f: newlines = [] for line in f.readlines(): newlines.append(line.replace('A', 'Orange')) with open('Stud.txt', 'w') as f: for line in newlines: f.write(line)
#!/usr/bin/python with open(FileName) as f: newText=f.read().replace('A', 'Orange') with open(FileName, "w") as f: f.write(newText)
最简单的方法是用正则expression式来做,假设你想遍历文件中的每一行(其中'A'将被存储),你做…
import re input = file('C:\full_path\Stud.txt), 'r') #when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file. So we have to save the file first. saved_input for eachLine in input: saved_input.append(eachLine) #now we change entries with 'A' to 'Orange' for i in range(0, len(old): search = re.sub('A', 'Orange', saved_input[i]) if search is not None: saved_input[i] = search #now we open the file in write mode (clearing it) and writing saved_input back to it input = file('C:\full_path\Stud.txt), 'w') for each in saved_input: input.write(each)