write multiple files at a time

前端 未结 5 484
长情又很酷
长情又很酷 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:39

    You can't make python look inside the list class for the write object as an iterable in the list comprehension. The list is not compatible with the write() method. In python lists are appended.

    Assuming your data file has new lines already in the file, create a filter object to remove blank lines then iterate:

    string1 = '128,129', '134, 167', '127,189'
    string2 = '154, 134', '156, 124', '138, 196'
    l1 = list(string1)
    l2 = list(string2)
    data = [l1, l2]
    f = open("inpt.data", "w")
    for val in data:
        f.write(str(val))
        f.write('\n')
    f.close()
    
    with open("inpt.data", "r", encoding='utf-8') as fs:
        reader = fs.read()
        file = reader.split('\n')
        file = filter(None, file)
    

    The simplest way:

    # create one file for each list of data (1) on every new line 
    i = 0
    for value in file:
        i += 1
        f = open("input_%s.data" % i, 'w')
        f.write(value)
    fs.close()
    

    The pythonic simple way:

    for i, line in enumerate(file):
        fi = open("input_%s.data" % i, 'w')
        fi.write(line)
    fs.close()
    

提交回复
热议问题