Reputation: 11
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:
Source Code:
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
Upvotes: 0
Views: 95
Reputation: 1420
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.
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])}")
name1.txt
0 1 2 3
name2.txt
0 4 5 6
name3.txt
0 7 8 9
Upvotes: 2
Reputation: 11090
The problem is that you're looping over all data for each file. Instead, you want to get only the data associated with that file. To do this, you can use enumerate()
to get a list index. Also, you do not need f.writelines()
because you're only writing one line. Instead, use f.write()
. Here's the code you're looking for:
data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
files = ['f1.txt', 'f2.txt', 'f3.txt']
for i, file in enumerate(files):
with open(file, 'w') as f:
f.write('0 ' + str(data[i]).replace('[', '').replace(']', '').replace(',', ''))
Upvotes: 1