我基本上是试图更新一行在保存的文件与新的更新编号,但它只留下一行在文件中。它感觉像是覆盖了整个文件,而不是更新它。我看了这里的其他问题,虽然他们给了我正确的模块来使用,我似乎无法找出我的问题。你知道吗
unique = 1
for line in fileinput.input('tweet log.txt', inplace=1):
if tweet_id in line: #checks if ID is unique, if it is not, needs to update it
tweet_fields = line.split(';')
old_count = tweet_fields[-2]
new_count = 'retweet=%d' % (int(tweet_retweet))
line = line.replace(old_count, new_count)
print line
unique = 0
if unique == 1: #if previous if didn't find uniqueness, appends the file
save_file = open('tweet log.txt', 'a')
save_file.write('id='+tweet_id +';'+
'timestamp='+tweet_timestamp+';'+
'source='+tweet_source+';'+
'retweet='+tweet_retweet+';'+'\n')
save_file.close()
我觉得这是一个非常简单的解决办法,但我显然错过了它。 提前谢谢!你知道吗
我认为您遇到的问题是由于您在输入的循环中的条件。当您将
fileinput.input
与inplace=1
参数一起使用时,它将重命名原始文件并添加一个“backup”扩展名(默认情况下为“.bak”),并将标准输出重定向到具有原始名称的新文件。你知道吗循环只打印正在编辑的行。因此,所有不匹配的行都将从文件中筛选出来。您可以通过打印迭代的每一行来解决这个问题,即使它不匹配。这是你循环的一个修改版本:
唯一的变化是将
print line
语句移出if
块。你知道吗相关问题 更多 >
编程相关推荐