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, should be written in '1.txt' and
data 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.
You are looping trough all the data on every iteration of
for files in folderand 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()
Your use of
zipmakes no sense.
zipis 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
datais a list of lists of rows (rather than a list of rows) you'll have to swap