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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With