简体   繁体   中英

CSV file creation error in python

I am getting some error while writing contents to csv file in python

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)

Error

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

How to fix it and what is the error?

You have error message - just read it. The file test_1/1/2013_.csv doesn't exist.

In the file name that you create - you use a[0][0] and in this case it result in 1/1/2013. Probably this two signs '/' makes that you are looking for this file in bad directory. Check where are this file (current directory - or in .test_1/1 directory.

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.

To ensure the path to a file exists you can combine os.makedirs and os.path.dirname .

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM