2 回答

TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
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貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超8個(gè)贊
for line in infile:
print line, infile
line = fun(line, infile.next())
break
break 離開(kāi)當(dāng)前循環(huán),因此它將僅在第一行運(yùn)行,然后停止。
為什么您的fun函數(shù)在文件而不是行上運(yùn)行?您已經(jīng)有了該行,因此沒(méi)有理由再次閱讀它,并且我認(rèn)為像這樣寫(xiě)回它是一個(gè)壞主意。嘗試使其與以下功能簽名一起使用:
def fun(line):
# do things
return changed_line
為了處理文件,您可以使用with語(yǔ)句使此操作更簡(jiǎn)單,更簡(jiǎn)單:
with open("filelocation", "a+") as infile:
for line in infile:
line = fun(line)
# infile is closed here
對(duì)于輸出,要寫(xiě)回您正在讀取的相同文件是相當(dāng)困難的,因此,我建議您只打開(kāi)一個(gè)新的輸出文件:
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))
或者,您可以讀入整個(gè)內(nèi)容,然后將其全部寫(xiě)回(但根據(jù)文件的大小,這可能會(huì)占用大量?jī)?nèi)存):
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)
添加回答
舉報(bào)