Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copy Each Line of a List into a Separate Text File

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(',', ''))

”’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading