I am basically trying to update a line in saved files with new updated number but it leaves only one line in the file. It feels like its overwriting over entire file rather than updating it. I looked at other questions here, and although they gave me right module to use I can’t seem to figure out the problem I am having.
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()
I feel like this has a very easy solution but I am clearly missing it.
Thanks in advance!
I think the issue you’re having is due to your conditional in the loop over the input. When you use
fileinput.inputwith theinplace=1argument, it renames the original file adding a “backup” extension (by default “.bak”) and redirects standard output to a new file with the original name.Your loop is only printing the line that you’re editing. Because of this, all the non-matching lines are getting filtered out of the file. You can fix this by printing each line you iterate over, even if it doesn’t match. Here’s an altered version of your loop:
The only change is moving the
print linestatement out of theifblock.