Trying to scrape from a file and write the scraped contents to another file?

Viewed 40

Warning: I'm new to coding and any constructive criticism is welcome

My goal: I'm trying to read and scrape a .txt for anything coming after a few specified characters (in this case it's '[CHAT] [@]'). Then I want to write that selected data to a new file.

This is purely for coding practice

with open("/Users/barge/Desktop/Untitled.txt", "r") as logsfile:
    for line in logsfile:
        if "[CHAT] [@]" in line:
            print(line[44], end='')  

with open("newtestfile.txt", "w+") as newfile:
    for eline in newfile:
        newfile.write(line[44])

logsfile.close()
newpyfile.close()

My issue: I'm not getting any errors in the terminal but my output file 'newtestfile.txt' is empty each time I run it. Line 7 should be writing all the characters after the 44th index of Untitled.txt right?

Thanks.

2 Answers

open yields an iterator (read notes) and line[44], isn't line[44] anymore when you try to write it to a file.

Try this instead:

with open("/Users/barge/Desktop/Untitled.txt", "r") as logsfile, open("newtestfile.txt", "w+") as newfile:
    for line in logsfile:
        if "[CHAT] [@]" in line:
            print(line[44], end='')  # prints everything to the right of index[44] for each line
            newfile.write(line[44])

Notes:

  • Understanding Python's "with" statement
  • with closes the file automatically
  • open() doesn't truly yields an iterator, but ratter a subclass of io.TextIOBase (read more here), calling it an iterator is a simplification of the underling process for better understanding.
  • I couldn't test the code.

Your issue is that the data is lost as soon as your upper loop exits. You will want to either have another with opening your output file under your first loop, or open the file for writing (using open() directly without the with) and using that each loop. Don't forget to flush and close your file once you're done.

Related