我是python的新手,并寻求一些帮助。我有一个包含当前数据的文本文件:
Tue Jun 25 **15** 336 0 0 0 0 0
Tue Jun 25 **04** 12682 0 0 0 0 0
Tue Jun 25 **05** 12636 0 0 0 0 0
Tue Jun 25 **06** 12450 0 0 0 0 0
Tue Jun 25 **07** 12640 0 0 0 0 0
我想浏览每一行并检查 是否大于12.如果它大于12我想从中减去12然后用新号码写回。
下面是我到目前为止的代码:
infile = open("filelocation", "a+") #open the file with the data above and append / open it
def fun (line, infile): # define a function to to go to position 12 - 14 (which is where the date in bod is) and set it to an integer
t = infile[12:14]
p = int(t)
if p > 12: # here is the logic to see if it is greater then 12 to subtract 12 and attempt to write back to the file.
p = p - 12
k = str(p)
infile.write(k)
else:
print p # probably not needed but i had it here for testing
return
# I was having an issue with going to the next line and found this code.
for line in infile:
print line, infile
line = fun(line, infile.next())
break
infile.close()
主要问题是它没有遍历每一行或进行更新。甚至可能有更好的方法来做我想做的事情,只是没有知识或理解某些功能的能力。任何有关这方面的帮助将非常感谢!
答案 0 :(得分:1)
for line in infile:
print line, infile
line = fun(line, infile.next())
break
break
离开当前循环,所以这只会在第一行运行,然后停止。
为什么你的fun
函数在文件而不是行上运行?你已经有了这条线,所以没有理由再读一遍,我认为像这样写回来是个坏主意。尝试使用此函数签名:
def fun(line):
# do things
return changed_line
为了处理文件,您可以使用with
statement使这更简单,更加万无一失:
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)
答案 1 :(得分:0)
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)