0

我真的是 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()

主要问题是它没有遍历每一行或进行更新。甚至可能有更好的方法来做我想做的事情,只是还没有知识或了解某些功能的能力。对此的任何帮助将不胜感激!

4

2 回答 2

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语句来使这个更简单和更简单:

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)
于 2013-06-26T20:32:50.967 回答
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)
于 2013-06-26T20:32:18.617 回答