Creating text files using python

I have a list in the format:

a=["C/C++","Java","Python"]

I am trying to create a text file for each element in the list using python as follows:

for i in a:
    temp=i+".txt"
    with open(temp,"w") as outfile:
          outfile.write("some value")

However am running into issues for the elements off the form "C/C++" as it is trying to interpret that as a dir.

 Traceback (most recent call last):
   File "<stdin>", line 3, in <module>
 IOError: [Errno 2] No such file or directory: 'C/C++.txt'

How do I overcome this??

Note-if the list element does not contain "/" in it, then the code created files for such elements.

Upvotes: 0

Views: 541

Answers (1)

pradyunsg
pradyunsg

Reputation: 19406

Well the problem is fairly simple.
A file name can't contain any of the following characters: /:*?<>|

So, just change the name to a valid one like C-C++

Upvotes: 4

Related Questions