我有一个非常大的文件,信息不对。取消python脚本中的next()函数
- 这一个
- 是
- XXX 123gt数1121
- 12345 FRE 233fre
- 问题的文件。
- 它包含
- XXX HY 456 EFE
- RTG 1215687 FWE
- 许多错误
- ,我想
- toget我写了一个脚本摆脱
。每当XXX遇到:
- 线被替换为自定义字符串(东西)。
- 下一行将被替换为另一个自定义字符串(stg)。
下面是脚本:
subject='problematic.txt'
pattern='xxx'
subject2='resolved.txt'
output = open(subject2, 'w')
line1='something'
line2='stg'
with open(subject) as myFile:
for num, line in enumerate(myFile, 1): #to get the line number
if pattern in line:
print 'found at line:', num
line = line1 #replace the line containing xxx with 'something'
output.write(line)
line = next(myFile, "") # move to the next line
line = line2 #replace the next line with 'stg'
output.write(line)
else:
output.write(line) # save as is
output.close()
myFile.close()
它与第一XXX发生效果很好,但不与subsequents。原因来自next()
,它推动迭代,因此我的脚本在错误的地方进行了更改。
这里是输出:
发现在行:6
代替:在线路3
发现
发现在行:3
在行:7
因此所做的更改不会在写的地方做......理想的情况下,取消next()
后,我改变了与2号线将解决我的问题行了,但我没有找到以前的()功能。任何人?谢谢!!
这听起来像你想要做的是* peek *在下一行而不改变循环? – mhlester
使用with-statement来打开文件的重点在于,您完成后不必显式关闭它。换句话说,'myFile.close()'行是完全不必要的。 :) – iCodez
你不需要''with''下的'for'循环吗?就像'for line in myFile:' – wnnmaw