How can I store an output print data?

Viewed 29

My script prints top 5 subreddits from specified redditor.



reddit = praw.Reddit(
    client_id="",
    client_secret="",
    password="",
    user_agent="",
    username="",
)


for submission in reddit.redditor("").top(limit=5):
    print(submission.subreddit) 

Im trying to store in txt file what is being printed.

I was trying to use this method:

f = open('file.txt', 'w+')
f.write(submission.subreddit)
f.close()

But received this error at the end

TypeError: write() argument must be str, not Subreddit

Any ideas how can I store subreddits in txt file?

1 Answers

When you are writing something to a file, but the something is not a string, you need to first convert it to a string.

str_subreddit = str(submission.subreddit)

However, there are better ways of doing what you're trying to do:

  • Use Unix shell to redirect output of your program to a file: python my_script.py > file.txt
    • To append instead of overwriting, use >>
    • This is arguably a better method, because it follows the Unix philosophy
  • print takes a file argument: print(str_subreddit, file=f)
    • You will of course have to open the file at the beginning of your program

Also, if you are trying to append to a file with f = open('file.txt', 'w+'), you want a not w+. w+ is something else.

Related