Search code examples
pythonreddit

print reddit scraping to file


I'd like to have the results of this query from Reddit to be redirected to a file. thanks

for comments in subreddit.stream.comments(skip_existing = True):
    if (time.time() - start_time) < 10:
        print(comments.body, comments.author)

Solution

  • If this is the only output of your file, python myPythonFile.py > fileToWrite.txt is the simplest solution in a shell environment.

    Otherwise you can write to the file from Python:

    # open the file
    with open('fileToWrite', 'w', encoding='utf-8') as f: 
        for comments in subreddit.stream.comments(skip_existing = True): 
            if (time.time() - start_time) < 10:
                f.write("{}, {}\n".format(comments.body, comments.author))