好的,基本上我正在尝试访问包含如下数据的文本文件:
John 01
Steve 02
Adam 15
我正在访问它,从每行中分割整数并从变量“days”中的每一行中减去一个。然后在从每一行中减去一个之后,我运行一个if语句来查看是否有任何行包含“0”,如果该行包含0它应该删除整行(数字和名称),然后用新的重新打印名称几天 - 1.我的代码在控制台中完美运行,并且名称打印完美,并且删除,我只是遇到了这样一个事实,即每行都打印了最后几天的值而不是它自己的值。例如:
Steve 14
Adam 14
虽然史蒂夫应该在01岁,但是他接受了亚当的14岁。我的代码附在下面:
global days
global names
with open('tracker.txt', 'r') as f:
for line in f:
days = line.strip()[-2:]
names = line.strip()[:-3]
days = int(days) - 1
print(names +" "+str(days))
if days == 0:
f = open("tracker.txt","r")
lines = f.readlines()
f.close()
f = open("tracker.txt","w")
for line in lines:
if line!=str(names)+ " 01" +"\n":
f.write(line[:-3]+ "" + str(days) + "\n")
f.close()
f.close()
答案 0 :(得分:1)
行。我不确定我理解你要做什么,但试试看:
import os
# The file name of our source file and the temporary file where we keep
# our filtered data before copying back over source file
source_file_name = 'tracker.txt'
temporary_file_name = 'tracker_temp.txt'
# Opening the source file using a context manager
with open(source_file_name, mode='r') as source_file:
# Opening our temporary file where we will be writing
with open(temporary_file_name, mode='w') as temporary_file:
# Reading each line of the source file
for current_line in source_file:
# Extracting the information from our source file
line_splitted = current_line.split()
current_name = line_splitted[0]
current_days = int(line_splitted[1])
# Computing and print the result
future_days = current_days - 1
print(current_name, future_days)
# Writing the name and the computed value
# to the temporary file
if future_days != 0:
output_line = "{} {:02}\n".format(current_name, future_days)
temporary_file.write(output_line)
# After we went through all the data in the source file
# we replace our source file with our temporary file
os.replace(temporary_file_name, source_file_name)
告诉我。那是你想要做的吗?没有?那么请告诉我们更多详情!