当行与我的lookup_keyword匹配时,我想替换每一行上的字符。我设法找到了以下解决方案。但是 finaljoin 只会在新文件上写入更改(只有受影响的行被写回)
如何在新文件中一起编写未受影响的行?
我知道我们可以使用 fileinput inplace 编辑,但更适合关键字替换。
Example input file,
123456789 [Thanos]
123456789 [Thanos]
123456789 [Thor]
123456789 [Loki]
Example output file,
1AA345KK789 [Thanos]
1AA345KK789 [Thanos]
Expected output file that I actually wanted.
1AA345KK789 [Thanos]
1AA345KK789 [Thanos]
123456789 [Thor]
123456789 [Loki]
lookup_keyword= "Thanos"
with open(filename) as myFile:
# myFile,1 means start reading the line at line number one.
# By default python will read start from 0.
for num, line in enumerate(myFile, 1):
if lookup_keyword in line:
#print ('Found at line:', num)
s = list(line)
s[1] = 'AA'
s[5] = 'KK'
# join the list to a original string form
finaljoin = "".join(s)
#print (finaljoin)
with open(new_filename, 'a+') as f:
f.write(finaljoin)
答案 0 :(得分:0)
输出文件只包含您实际写入的行。
如果Thanos在该行中,则修改该行,打开输出文件,并将更改后的行附加到该行。
但如果没有,你什么都不做,所以什么也没写。
你可以这样解决:
for num, line in enumerate(myFile, 1):
#print ('Found at line:', num)
s = list(line)
if lookup_keyword in line:
s[1] = 'AA'
s[5] = 'KK'
# join the list to a original string form
finaljoin = "".join(s)
#print (finaljoin)
with open(new_filename, 'a+') as f:
f.write(finaljoin)
这样,无论您是否修改了新行,您都会创建新行并将其附加到新文件中。
可替换地:
for num, line in enumerate(myFile, 1):
if lookup_keyword in line:
#print ('Found at line:', num)
s = list(line)
s[1] = 'AA'
s[5] = 'KK'
# join the list to a original string form
finaljoin = "".join(s)
else:
finaljoin = line
with open(new_filename, 'a+') as f:
f.write(finaljoin)
这样,当你不想修改它时,你不会浪费精力去分裂和重新加入这条线,而且它并没有那么复杂。
答案 1 :(得分:0)
<强> input_file.txt 强>
Example input file,
123456789 [Thanos]
123456789 [Thanos]
123456789 [Thor]
123456789 [Loki]
<强> Script.py 强>
input_file_name = 'input_file.txt'
output_file_name = 'output_file.txt'
lookup_keyword= "Thanos"
with open(input_file_name) as input_file:
next(input_file) # skip first line
with open(output_file_name, 'w') as output_file:
for input_line in input_file:
if lookup_keyword in input_line:
input_list = list(input_line)
input_list[1] = 'AA'
input_list[5] = 'KK'
output_line = ''.join(input_list)
else:
output_line = input_line
output_file.write(output_line)