1

I have a python list ['a','b','c'] that's generated inside a for loop. I would like to write each element of the list to a new file.

I have tried:

counter = 0
for i in python_list:
    outfile = open('/outdirectory/%s.txt') % str(counter) 
    outfile.write(i)
    outfile.close()
    counter += 1 

I get an error:

IOError: [Erno 2] No suchfile or directory. 

How can I programmatically create and write files in a for loop?

Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63
mech
  • 96
  • 1
  • 9

3 Answers3

2

You're not passing a mode to open, so it's trying to open in read mode.

outfile = open('/outdirectory/%s.txt' % str(counter), "w") 

Try this:

out_directory = "/outdirectory"
if not os.path.exists(out_directory):
    os.makedirs(out_directory)

for counter in range(0, len(python_list)):
    file_path = os.path.join(out_directory, "%s.txt" % counter)
    with open(file_path, "w") as outfile:
        outfile.write(python_list[counter])
ErlVolton
  • 6,714
  • 2
  • 15
  • 26
2

Some suggestions:

  • Use the with statement for handling the files [docs].
  • Use the correct file open mode for writing [docs].
  • You can only create files in directories that actually exist. Your error message probably indicates that the call to open() fails, probably because the directory does not exist. Either you have a typo in there, or you need to create the directory first (e.g., as in this question).

Example:

l = ['a', 'b', 'c']
for i, data in enumerate(l):
    fname = 'outdirectory/%d.txt' % i
    with open(fname, 'w') as f:
        f.write(data)
Community
  • 1
  • 1
moooeeeep
  • 31,622
  • 22
  • 98
  • 187
2

basically the message you get is because you try to open a file named /outdirectory/%s.txt. A following error as ErlVolton show is that you don't open your file in writing mode. additionaly you must check that you directory exist. if you use /outdirectory it means from the root of the file system.

Three pythonic additional: - enumerate iterator which autocount the item in your list - with statement autoclose your file. - format can be a little clearer than % thing

so the code could be written in the following

for counter,i in enumerate(python_list):
    with open('outdirectory/{}.txt'.format(counter),"w") as outfile:
        outfile.write(i)

PS: next time show the full back trace

Xavier Combelle
  • 10,968
  • 5
  • 28
  • 52