Looping and writing through text files

I have multiple text files in a folder, let's say: '1.txt', '2.txt', etc. I have a list called data that contains different arrays. The first array of the data, data[0], should be written in '1.txt' and data[1] to '2.txt', and so on. So far I have the following code:

for files in folder:
    for i in range(0,len(data)):
        data = zip(data[i])
        with open (files, "w") as f:
            writer = csv.writer(f,delimiter='\t')
            writer.writerows(data)
        quit() 

This works, such that every text file contains the data of the last array, as I'm not yet looping through the datafiles. How can I select file number i such that I can write the corresponding data[i]? I tried different things, but keep getting errors. Could someone help me out? Much appreciated.

2 answers

  • answered 2019-12-09 12:39 Samuel Middendorp

    You are looping trough all the data on every iteration of for files in folder and thus the last entry of the data array will always be the content of every txt file since the data is overwritten on every iteration of for i in range(0,len(data)):

    If there is a set amount of data that corresponds to a set amount of files we can simplify the loop:

    for i in range(0,len(files)):
        dataToBeWritten = data
        with open (files[i], "w") as f:
             writer = csv.writer(f,delimiter='\t')
             writer.writerows(dataToBeWritten)
    quit() 
    

  • answered 2019-12-09 12:45 Masklinn

    Your use of zip makes no sense. zip is used to pair multiple sequence together e.g. zip([1, 2, 3], ['a', 'b', 'c']) returns [(1, 'a'), (2, 'b'), (3, 'c')]. Zipping a single sequence is equivalent to just using the sequence directly.

    for filename, row in zip(folder, data):
        with open(filename, 'w') as f:
            csv.writer(f, delimiter='\t').writerow(row)
    

    should do more or less what I understand you ask for. If data is a list of lists of rows (rather than a list of rows) you'll have to swap writerows for writerow.