Python - creating a file for each item in a list

I am trying to use python to create a separate text file for each 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 the target text file. The second list is created using the lines from the first list with some addition (in the case of adding "time" to the end). In my third line, I ran into problems. I want to create a separate 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 element of the list was “healthy time” and my second element of the list was “meal time”, text files called “healthy time.txt” and “foodtime.txt” will be created.

I seem to have run into a problem with the open command, but I searched extensively and found nothing regarding the use of open in the context of the list.

+4
source share
2 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 leads to a lazy evaluation, so you don’t loop, don’t loop, and don’t loop, etc.

then correct your line ( , this is the actual problem causing the 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 all your code will be

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 scroll through the list once instead of three times

the suggestion to use the filePath variable to form your file name is also very good

+5
source

. open.

for item in List2:
    filePath = '/home/user/Documents/%s.txt' % (item)
    open(filePath, 'w')
+3

Source: https://habr.com/ru/post/1535066/


All Articles