Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write multiple files at a time

Tags:

python

file

I have a file with 196 list in it,and I want to create new 196 output files and write each of the list in a new file, so that I will have 196 output files each containing 1 list of input data Here is the input file:

"['128,129', '116,118', '108,104', '137,141', '157,144', '134,148', '138,114', '131,138', '248,207', '208,247', '246,248', '101,106', '131,115', '119,120', '131,126', '138,137', '132,129']"
"['154,135', '151,147', '236,244', '243,238', '127,127', '125,126', '122,124', '123,126', '127,129', '122,121', '147,134', '126,132', '128,137', '233,222', '222,236', '125,126']"

.....here for eg, I have given only 2 list but total 196 list are present. Output should be:

file 1 :

128,129
116,118
108,104

file2 :

154,135
151,147
236.244

Current code:

fn = open("/home/vidula/Desktop/project/ori_tri/inpt.data","r")
fnew = fn.read()
fs = fnew.split('\n')
for value in fs:
    f = [open("/home/vidula/Desktop/project/ori_tri/input_%i.data" %i,'w') for i in range(len(list_of_files))]
    f.write(value)
    f.close()

Error: list do not attribute write.

like image 794
shreya Avatar asked Dec 10 '12 09:12

shreya


2 Answers

Your current code is loading everything into memory, which is quite unnecessary, then it is making a list in a place that is not appropriate, hence your error. Try this:

fn = open("/home/vidula/Desktop/project/ori_tri/inpt.data","r")
for i, line in enumerate(fn):
    f = open("/home/vidula/Desktop/project/ori_tri/input_%i.data" %i,'w')
    f.write(line)
    f.close()

This will just write each line as it was to each file. Look up the enumerate function I used to do the indexing.

Having done this, you will still need to write parsing logic to turn each line into a series of lines...I'm not going to do that for you here, since your original code didn't really have logic for it either.

like image 114
John Zwinck Avatar answered Oct 20 '22 00:10

John Zwinck


your f is a list of files, you have to loop through it:

for file in f:
   file.write(value)
like image 45
Samuele Mattiuzzo Avatar answered Oct 20 '22 00:10

Samuele Mattiuzzo