我正在制作打开txt文件并用给定行的1替换前0的程序。现在,它仅打印已编辑的行,但我希望它打印所有行。我正在使用python 3.1。
line_number = 3
with open(filename, "r") as f:
number = 0
for line in f:
number += 1
if line_number == number:
content = line.replace("0","1",1)
savefile = filename[:4] + ".tmp"
with open(savefile, "w") as f:
f.write(content)
os.remove(filename)
os.rename(savefile, filename)
文本文件:
0 Dog
0 Cat
0 Giraffe
0 Leopard
0 Bear
答案 0 :(得分:2)
您需要将每个未更改的行写入savefile
:
import os
filename = 'input.txt'
line_number = 3
savefile = filename[:4] + ".tmp"
with open(filename, "r") as f:
with open(savefile, "w") as fout:
number = 0
for line in f:
number += 1
if line_number == number:
content = line.replace("0","1",1)
fout.write(content)
else:
# Write unchanged lines here
fout.write(line)
os.remove(filename)
os.rename(savefile, filename)
答案 1 :(得分:0)
您尝试过这样的事情吗?
filename = "./test.txt"
with open(filename) as f:
lines = f.readlines()
# the element with index 2 is the 3-th element
lines[2] = lines[2].replace("0","1",1)
with open(filename, 'w') as f:
[f.write(line) for line in lines]
输出(./test.txt
):
0 Dog
0 Cat
1 Giraffe
0 Leopard
0 Bear
您可以读取文件并将其保存到列表中。然后,您可以对列表中的每个项目(或特定元素)执行特定操作,并将结果保存在同一文件中。您不需要.tmp
文件,也不需要删除和重命名文件。
修改:
fileinput
还有另一种方法(感谢@PeterWood)
import fileinput
with fileinput.input(files=('test.txt',), inplace=True) as f:
for line in f:
if fileinput.lineno() is 3:
print(line.replace("0", "1", 1).strip())
else:
print(line.strip())