CSV file creation error in python
<p>I am getting some error while writing contents to csv file in python</p>

<pre><code>import sys  

reload(sys)  
sys.setdefaultencoding('utf8')
import csv
a = [['1/1/2013', '1/7/2013'], ['1/8/2013', '1/14/2013'], ['1/15/2013', '1/21/2013'], ['1/22/2013', '1/28/2013'], ['1/29/2013', '1/31/2013']]


f3 = open('test_'+str(a[0][0])+'_.csv', 'at')
writer = csv.writer(f3,delimiter = ',', lineterminator='\n',quoting=csv.QUOTE_ALL)
writer.writerow(a)
</code></pre>

<p>Error</p>

<pre><code>Traceback (most recent call last):
  File "test.py", line 10, in &lt;module&gt;
    f3 = open('test_'+str(a[0][0])+'_.csv', 'at')
IOError: [Errno 2] No such file or directory: 'test_1/1/2013_.csv'
</code></pre>

<p>How to fix it and what is the error?</p>

<p>It's probably due to the directory not existing - Python will create the file for you if it doesn't exist already, but it won't automatically create directories.</p>

<p>To ensure the path to a file exists you can combine <a href="https://docs.python.org/3/library/os.html#os.makedirs" rel="nofollow">os.makedirs</a> and <a href="https://docs.python.org/3/library/os.path.html#os.path.dirname" rel="nofollow">os.path.dirname</a>.</p>

<pre><code>file_name = 'test_'+str(a[0][0])+'_.csv'

# Get the directory the file resides in
directory = os.path.dirname(file_name)

# Create the directories
os.makedirs(directory)

# Open the file
f3 = open(file_name, 'at')
</code></pre>

<p>If the directories aren't desired you should replace the slashes in the dates with something else, perhaps a dash (<code>-</code>) instead.</p>

<pre><code>file_name = 'test_' + str(a[0][0]).replace('/', '-') + '_.csv'
</code></pre>

python csv