Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Reading and writing files
#1
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
Quote
#2
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.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Writing list as a file, then reading that file as a list Zoastria_Balnala 3 144 Oct-17-2019, 07:54 PM
Last Post: Zoastria_Balnala
  Reading DBF files from Amazon s3 throwing error - 'int' object has no attribute 'isa abeesm 1 169 Sep-22-2019, 05:49 PM
Last Post: ndc85430
  Problem with reading and writing to file. darktitan 2 223 Jul-20-2019, 06:06 PM
Last Post: darktitan
  Reading PCAP FIles Variables 5 440 Apr-26-2019, 06:05 AM
Last Post: buran
  Python 2.7.13 Issue Reading .txt files Properly username1145 3 362 Mar-24-2019, 03:08 PM
Last Post: username1145
  reading csv and writing csv chawas 2 564 Aug-23-2018, 09:28 AM
Last Post: chawas
  Reading Excel files and creating an output tms21 1 584 Aug-06-2018, 09:02 PM
Last Post: nilamo
  reading 2 files concurrently Skaperen 3 692 Jun-01-2018, 07:07 AM
Last Post: Skaperen
  using subpocess for both reading and writing simultaneously dauriac 11 2,401 May-30-2018, 10:09 PM
Last Post: killerrex
  copy files from one destination to another by reading filename from csv Prince_Bhatia 3 2,111 Feb-27-2018, 10:56 AM
Last Post: Prince_Bhatia

Forum Jump:


Users browsing this thread: 1 Guest(s)