0

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?

3
  • 3
    The error says that the file 2013_.csv or the directory test_1/1 does not exists. You may need to create the folder first before trying to create the file you want to write to. Commented Sep 14, 2016 at 7:10
  • I agree with @AvihooMamka. Do you really have the file there? Commented Sep 14, 2016 at 7:13
  • Whenever you want to deal with file paths use 'os.path'). Using string manipulation like you are doing is a bag of fail waiting to catch you out at every stage. Commented Sep 14, 2016 at 7:37

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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'

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.