CCDMT 6 days ago

Python, lines to lists

I have a txt file and I want to save each line as a list in a new file with fname as the new file name. But the output is not being saved. What am I missing ?

import csv

with open('file.txt', 'rU') as csvfile:
    reader = csv.reader(csvfile, delimiter='\t')
    i = 1
    for line in reader:
        fname = line[0] + line[1]
        #print fname
        with open(fname, 'w') as out:
            out.write(line)
        i +=1

Answers


宏杰李 6 days ago

Change:

with open(fname, 'w') as out:
            out.write(line) 

To:

with open(fname, 'a') as out:
        out.write(line)

w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

Better way:

import csv

with open('file.txt', 'rU') as csvfile, open(fname, 'w') as out:
    reader = csv.reader(csvfile, delimiter='\t')
    i = 1
    for line in reader:
        fname = line[0] + line[1]
        out.write(line)


racket99 6 days ago

You cannot write a list so change penultimate line to **out.write(str(line))**

import csv

with open('file.txt', 'rU') as csvfile:
    reader = csv.reader(csvfile, delimiter='\t')
    i = 1
    for line in reader:
        fname = line[0] + line[1]
        #print fname
        with open(fname, 'w') as out:
 ------>    out.write(str(line))
        i +=1

Post Status

Asked in 6 days ago
Viewed 3,999 times
Voted 11
Answered 2 times

Search




Leave an answer