Search code examples
pythonfiledictionarytraversal

File indexing issue in python


for this function, i need to traverse through a file and count each line based on certain signifiers. If that certain signifier is present in the line, i need to add the string as a key to the dictionary and increment its value by one each time its present. I am not outright looking for the answer, I am just lost as to what I have done wrong and where I can proceed from here.

Both of the counter variables and the dictionary are returning empty. I need them to return the values based on what is present on a given file.

file line example:

RT @taylorswift13: Feeling like the luckiest person alive to get to take these brilliant artists out on tour w/ me: @paramore, @beabad00bee & @OwennMusic. I can’t WAIT to see you. It’s been a long time coming 🥰

code:

def top_retweeted(tweets_file_name, num_top_retweeted):
    total_tweets = 0
    total_retweets = 0
    retweets_users = {}
    
    f_read = open(tweets_file_name, "r")
    f_write = open(tweets_file_name, "w")
    
    lines = f_read.readlines()
    
    for line in lines:
        total_tweets =+1
        elements = line.split(":")
        for element in elements:
            if "RT" in element:
                total_retweets =+1
                user_name = element.split()    
                retweet_users[user_name]=+1
    
    print("There were " + str(total_tweets) + " tweets in the file, " + str(total_retweets) + " of which were retweets")

    return retweets_user

Solution

  • f_read = open(tweets_file_name, "r")
    f_write = open(tweets_file_name, "w")
    

    You're opening the file for reading and then also opening it for writing, which destroys the existing contents.