write multiple files at a time

前端 未结 5 490
长情又很酷
长情又很酷 2021-01-13 20:04

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

5条回答
  •  花落未央
    2021-01-13 20:30

    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.

提交回复
热议问题