Write only part of a line to a file

I want to clear my output and write only the part of the line that I need for the new file, and not for the entire line. This is the relevant coding section:

counter = 1

for line in completedataset:
    print counter
    counter +=1

    for t in matchedLines:
       if t in line[:line.find(',')]:
            smallerdataset.write(line)
            break

Here is an example of data:

NOVE1780418 "," --- "," JAX17054099 "," 5 "," 156323558 ", etc. for the line.

I want to write only up to the number up to the 3rd comma. I need help changing the write-only line of a record to the third comma. This file is very large, and I hope that any new code will not slow down the program, but rather speed it up. Thanks bob

+3
source share
2 answers

It should be as simple as that ...

for line in infile:
    line = line.strip().split(',')
    outfile.write(','.join(line[:3]) + '\n')
+4
for line in infile:
    line = line.strip().split(',',3)
    outfile.write(','.join(line[:-1]) + '\n')

"," , csv

+1

Source: https://habr.com/ru/post/1758270/


All Articles