我读取了一个输入文件,并尝试通过将日期中的单位数'day‘值替换为两位数的'day’值来重新格式化未完全形成的日期字段。一开始似乎工作得很好,然后我注意到输入文件有(279)条记录,但输出却写有(615)条记录。许多(如果不是全部)个位数的日期值按预期进行了替换,但这些记录的原始版本似乎也被写到了输出中。当然,预期输出也会有(239)个记录?(脚本运行时不会抛出任何错误)。
replacements = {'/1':'/01', '9/':'09/', '7/':'07/'}
file2 = open(r"c:\users\liddvdp\desktop\IBC CAP OUT.txt", "w")
with open(r"c:\users\liddvdp\desktop\IBC CAP.txt", "r") as reader:
for line in reader:
for src, target in replacements.items():
line = line.replace(src, target)
file2.write(line)发布于 2020-11-08 03:47:22
你应该这样写:
replacements = {'/1':'/01', '9/':'09/', '7/':'07/'}
file2 = open(r"c:\users\liddvdp\desktop\IBC CAP OUT.txt", "w")
with open(r"c:\users\liddvdp\desktop\IBC CAP.txt", "r") as reader:
for line in reader:
for src, target in replacements.items():
line = line.replace(src, target)
file2.write(line)否则,您将每行编辑三次,并在输出文件中写入三次。
https://stackoverflow.com/questions/64731432
复制相似问题