I have two lists of equal length. One contains the names of the files I would like to create while the other is a 2-d list that has data I would like to copy into a text file with a name from the list. I want each element from the 2D list to have its own separate text file. The example code is as follows:
”’
example_data = [[1,2,3],[4,5,6],[7,8,9]]
example_names = ['name1.txt', 'name2.txt', 'name3.txt']
for name in example_names:
for ele in example_data:
with open(name, 'w') as f:
f.writelines('0 ' + str(ele).replace('[', '').replace(']', '').replace(',', ''))
”’
Current Output:
name1.txt,
data within file: 0 7 8 9
name2.txt,
data within file: 0 7 8 9
name3.txt,
data within file: 0 7 8 9
Expected output:
name1.txt,
data within file: 0 1 2 3
name2.txt,
data within file: 0 4 5 6
name3.txt,
data within file: 0 7 8 9
>Solution :
Logic
You can use zip to get both the element side by side and use str.join to convert list to str and as it’s list of int you need to convert every individual element to str type.
Solution
Source Code
example_data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
example_names = ["name1.txt", "name2.txt", "name3.txt"]
for file_name, data in zip(example_names, example_data):
with open(file_name, "w") as f:
f.write(f"0 {' '.join([str(x) for x in data])}")
Output
name1.txt
0 1 2 3
name2.txt
0 4 5 6
name3.txt
0 7 8 9