2 回答

TA贡献1773条经验 获得超3个赞
inp = open("filelocation").readlines()
with open("filelocation", "w") as out:
for line in inp:
t = line[12:14]
p = int(t)
if p>12:
line = '{}{:02}{}'.format(line[:12], p-12, line[14:])
out.write(line)

TA贡献1789条经验 获得超8个赞
for line in infile:
print line, infile
line = fun(line, infile.next())
break
break 离开当前循环,因此它将仅在第一行运行,然后停止。
为什么您的fun函数在文件而不是行上运行?您已经有了该行,因此没有理由再次阅读它,并且我认为像这样写回它是一个坏主意。尝试使其与以下功能签名一起使用:
def fun(line):
# do things
return changed_line
为了处理文件,您可以使用with语句使此操作更简单,更简单:
with open("filelocation", "a+") as infile:
for line in infile:
line = fun(line)
# infile is closed here
对于输出,要写回您正在读取的相同文件是相当困难的,因此,我建议您只打开一个新的输出文件:
with open(input_filename, "r") as input_file:
with open(output_filename, "w") as output_file:
for line in input_file:
output_file.write(fun(line))
或者,您可以读入整个内容,然后将其全部写回(但根据文件的大小,这可能会占用大量内存):
output = ""
with open(filename, "r") as input_file:
for line in input_file:
output += fun(line)
with open(filename, "w") as output_file:
output_file.write(output)
添加回答
举报