我正在尝试通过用output.dat
替换超过1
的值来处理文件1
。
例如,如果文件包含如下数字:
1
2
3
4
我希望输出为:
1
1
1
1
答案 0 :(得分:1)
如果文件不是很大,请阅读过滤任何行的所有行> 1,然后重新打开覆盖:
with open(infile) as f:
lines = ["1\n" if int(line) > 1 else line for line in f]
with open(infile, "w") as out:
out.writelines(lines)
输出:
1
1
1
1
这假设所有行都只包含您的示例中的数字。
或fileinput.input
使用inplace=True
:
import fileinput
for line in fileinput.input(infile,inplace=True):
if int(line) > 1:
print("1")
else:
print(line.rstrip()) # python3 print(line,end="")
按原样保留前两行:
with open(infile) as f:
skip = next(f),next(f)
lines = ("1\n" if int(line) > 1 else line for line in f)
with open(infile, "w") as out:
out.writelines(skip)
out.writelines(lines)
或者使用枚举,留下索引为<的前n行。 1:
with open(infile) as f:
lines = ("1\n" if int(line) > 1 and ind > 1 else line for ind, line in enumerate(f))
with open(infile, "w") as out:
out.writelines(lines)