Reading and writing files - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Reading and writing files (/thread-20378.html) |
Reading and writing files - JakeHoward4 - Aug-07-2019 Hello, I have a file with roughly 30,000 lines in it. At the end of each line is a sport (ex: baseball, basketball, football, etc.). I am trying to pull out all the lines that end in the word baseball and write them into a new file. Here is my code: fhand = open('Twwetdumpsimple.csv', 'r') final = open("TweetDumpBaseballOnly.csv", "w") for line in fhand: if line.endswith(",baseball"): final.write(line) final.write("\n") else: continue final.close()The code runs, however, it only writes one line of data into the new file. This also happens to be the last line of the original file. I don't know why the other lines that end in baseball aren't being written in. Any help would be appreciated. Thanks, Jake RE: Reading and writing files - Yoriz - Aug-07-2019 Can you list some sample contents of the input file that results in only one line of data in the new file. Bear in mind the following line = ',baseball\n' print(line.endswith(',baseball')) line = line.strip() print(line.endswith(',baseball')) if the line end in special characters it won't match endswith .
|