Rk_23
Rk_23

Reputation: 193

Printing out elements of list into separate text files in python

Im new to python programming and need some help with some basic file I/O and list manipulation.

currently i have a list (s) that has these elements in it:

['taylor343', 'steven435', 'roger101\n']

what i need to do is print each line into new text files with only the 1 element in the text files as shown below:

file1.txt
taylor343

file2.txt
steven435

file3.txt
roger101

Im currently trying to work with this using a loop but i can only output into 1 text file

for x in list:  
    output.write(x+"\n")

How can i get it to write every single line of list into new text files (not just one)

Thank you

Upvotes: 2

Views: 4422

Answers (2)

Chris Gregg
Chris Gregg

Reputation: 2382

@Joe Kington wrote an excellent answer that is very pythonic. A more verbose answer that might make understanding what is going on a little easier would be something like this:

s = ['taylor343', 'steven435', 'roger101\n']

f = open("file1.txt","w")
f.write(s[0]+"\n")
f.close()

f = open("file2.txt","w")
f.write(s[1]+"\n")
f.close()

f = open("file3.txt","w")
f.write(s[2]) # s[2] already has the newline, for some reason
f.close()

If I were to make it a bit more general, I'd do this:

s = ['taylor343', 'steven435', 'roger101'] # no need for that last newline
for i,name in enumerate(s):
    f = open("file"+str(i+1)+".txt","w")
    f.write(name+"\n")
    f.close()

Upvotes: 2

Joe Kington
Joe Kington

Reputation: 284970

You need to open each new file you want to write into. As a quick example:

items = ['taylor', 'steven', 'roger']
filenames = ['file1', 'file2', 'file3']

for item, filename in zip(items, filenames):
    with open(filename, 'w') as output:
        output.write(item + '\n')

Upvotes: 6

Related Questions