python:检查然后更新文本文件中的值

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

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


慕妹3242003
浏览 232回答 2
2回答

慕容3067478

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)

拉丁的传说

for line in infile:    print line, infile    line = fun(line, infile.next())    breakbreak 离开当前循环,因此它将仅在第一行运行,然后停止。为什么您的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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python