Ebin Davis
Ebin Davis

Reputation: 6139

How to write each element of list in multiple text file?

I am trying to write each element inside a list to multiple files.

Suppose I have a list:

value = [ 'abc' , 'def' , 'ghi' ]

How can write each element inside the list value to multiple files? So, in this case, there should be three text files be created and each value abc,def and ghi in each file.

I have a simple python script which will write all the list values to a single text file:

value = ['a','b','c']

for i in value:

   f=open('/tmp/new.txt','a')
   f.write(i)

How can I achieve my use-case? Thanks in advance.

Upvotes: 0

Views: 1147

Answers (4)

kamses
kamses

Reputation: 465

If you're trying to write every value contained in the list to all n files, then you could just iterate through the file-writing commands, f.write() below, using a for loop. You're only going to write to each file once, so no need to worry about open()'s 'a' or 'w+' modes. Then you could print all elements of the list to each file using the str.join() method. I've used newline as the delimiter below, but you could choose anything.

Here's how I changed your code to do this...

value = ['a','b','c']
for i in range(len(value)):
    with open("new_%d.txt" % i, 'w') as f:
        f.write('\n'.join(value))

Notice also the use of with to open each file. This is recommended best practice in python as it deals with clean-up of the file object that you create with open(). That is, you don't need to explicitly close the file after your done with f.close(), which can be easy to forget.

If you are set on starting with new_1.txt (versus new_0.txt, which is what will happen with the above code) then change the call to for to something like this:

for i in range(1,len(value)+1):

or change the call to with to:

with open("new_%d.txt" % (i+1), 'w') as f:

Upvotes: 2

Austin
Austin

Reputation: 26057

Use w+ file mode. It opens an existing file or create if file doesn't already exist and write:

value = ['a','b','c']

for x in value:
   with open(f'/tmp/new{x}.txt','w+') as f:
       f.write(x)

Upvotes: 0

Nitin Bhojwani
Nitin Bhojwani

Reputation: 712

Below should work:

value = ['a','b','c']

for i in range(len(value)):

   f=open('/tmp/new_%s.txt' % i ,'a')
   f.write(value[i])

Upvotes: 0

blhsing
blhsing

Reputation: 107134

You can do the following:

for n, i in enumerate(value, 1):
    with open('/tmp/new{}.txt'.format(n), 'a') as f:
        f.write(i)

Upvotes: 0

Related Questions