Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Creating a file for each item in a list

I am trying to use python to create an individual text file for every item in a list.

List = open('/home/user/Documents/TestList.txt').readlines()
List2 = [s + ' time' for s in List]
for item in List2 open('/home/user/Documents/%s.txt', 'w') % (item)

This code should generate a list from a target text file. A second list is generated using the strings from the first list with some appendage (in the case, adding ' time' to the end). My third line is where I'm running into problems. I want to create an individual text file for each item in my new list where the name of the text file is the string of that list item. Example: If my first list item was 'healthy time' and my second list item was 'food time', text files called "healthy time.txt" and "food time.txt" would be generated.

It appears i'm running into an issue with the open command, but I have searched extensively and found nothing regarding using open in the context of a list.

like image 930
userPinealbody Avatar asked Feb 13 '23 07:02

userPinealbody


1 Answers

first use generators

List = open("/path/to/file") #no need to call readlines ( a filehandle is naturally a generator of lines)
List2 = (s.strip() + ' time' for s in List) #calling strip will remove any extra whitespace(like newlines)

this causes lazy evaluation so you are not looping and looping and looping etc

then fix your line (this is the actual problem that is causing errors in your program)

for item in List2:
    open('/home/user/Documents/%s.txt'%(item,), 'w') 
           # ^this was your actual problem, the rest is just code improvements

so your whole code becomes

List = open("/path/to/file") #no need to call readlines ( a filehandle is naturally a generator of lines)
List2 = (s.strip() + ' time' for s in List)
for item in List2: #this is the only time you are actually looping through the list
    open('/home/user/Documents/%s.txt'%(item,), 'w') 

now you only are looping through the list one time instead of 3 times

the suggestion to use a filePath variable to form your filename is also a very good one

like image 117
Joran Beasley Avatar answered Feb 16 '23 02:02

Joran Beasley