繁体   English   中英

Python无法正确编辑文件

[英]Python not editing file correctly

应该很容易解决,但是我在这里看不到问题。

a = 18
b = 30
c = 00
input = open('13.gpx', 'r')
output = open('14.gpx', 'w')
for line in input.readlines():
    if line == '<time>2014-01-19T18:30:00Z</time>':
        d = str(int(a))
        e = str(int(b))
        f = str(int(c))
        output.write('<time>2014-01-19T' + d + ':' + e + ':' + f + 'Z</time>')
        c = c + 18.4712
        if c >= 60:
            b = b + 1
            c = c - 60
        else:
            print('hi')
        if c >= 60:
            a = a + 1
            b = b - 60
        else:
            print('hi')
    else:
        output.write(line)

我已经尝试了很多方法,但是它始终只是打印出原始文件,并且不会更改任何时间戳。

您的代码逻辑是:

对于文件中的每一行:

  1. 如果它是'<time>2014-01-19T18:30:00Z</time>' ,则构建该行的精确副本并将其写入输出文件; 要么
  2. 如果不是,则直接将其直接写入输出文件。

您期望在两个文件之间进行什么更改?

文件中的文本行以换行符结尾,因此您的相等性测试将不起作用:

if line == '<time>2014-01-19T18:30:00Z</time>':

从行的开头和结尾删除空格:

if line.strip() == '<time>2014-01-19T18:30:00Z</time>':

无需再次将整数强制转换为int ,并且如果使用字符串格式,则也无需强制转换为str()

output.write('<time>2014-01-19T{}:{}:{}Z</time>'.format(a, b, int(c))

您可能需要将这三个变量重命名为hoursminutesseconds ,并修复if c >= 60:行时出现的错误; 您最可能希望其中一个测试分钟,另一个测试秒。 现在,您仅测试秒值( c )是否溢出两次。

您也不需要使用file.readlines() 您可以直接在文件对象上循环; 它会产生以下行:

for line in input:

我将使用与input不同的名称; 您现在正在屏蔽内置的input()函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM