为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕妹3242003 2021-03-30 21:10:16
我真的是python新手,正在寻找一点帮助。我有一个包含当前数据的文本文件:Tue Jun 25 **15** 336 0 0 0 0 0Tue Jun 25 **04** 12682 0 0 0 0 0 Tue Jun 25 **05** 12636 0 0 0 0 0Tue 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 itdef 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())    breakinfile.close()主要问题是它没有遍历每行或进行更新。甚至可能有更好的方法来做我要尝试做的事情,就是只是不了解或不了解某些功能的功能。任何帮助,将不胜感激!
查看完整描述

2 回答

?
慕容3067478

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)


查看完整回答
反对 回复 2021-04-06
?
拉丁的传说

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)


查看完整回答
反对 回复 2021-04-06
  • 2 回答
  • 0 关注
  • 231 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号