0

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.

2
  • And the three text files should be called...? Commented Aug 11, 2018 at 16:38
  • @Tomalak it can be called by any name. new1, new2....newn will be better Commented Aug 11, 2018 at 16:39

4 Answers 4

2

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:
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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])

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.