Python Forum

Full Version: Reading and writing files
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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'))
Output:
False True
if the line end in special characters it won't match endswith.