陳俊良
陳俊良

Reputation: 319

How to save csv file into a specific path?

Recently, i had a project is to save some data as a csv file and save it in the absolute path. Here is my code.

import csv
a=[1,2,3,4,5,6,7,8,9]
with open("C:/test.csv","w") as f:
    writer = csv.writer(f)
    writer.writerows(a)

but it shows some error like this

Traceback (most recent call last):
  File "C:/Users/rickchen/Desktop/save1.py", line 3, in <module>
    with open("C:/test.csv","w") as f:
IOError: [Errno 13] Permission denied: 'C:/test.csv'

Can any master help me? Thank you very much ^_^

Upvotes: 0

Views: 9963

Answers (1)

Martin Evans
Martin Evans

Reputation: 46759

You possibly don't have write permission to write to the root of your C drive. You have a few alternatives to try:

  1. Run Python with Administrator privileges. This obviously depends on how you are running your script. For example, if you are starting a command prompt and running the script in that, right click on it and select "Run as Administrator".

  2. Use Windows to give your user account write access to your C:\ root folder.

  3. Possibly make sure the output file is not already open in another application.

  4. Ideally you should write to a more suitable folder. It is straight forward for example to write the output either to your Desktop, or to your Documents folder.

Your script could be updated as follows:

import csv
import os

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

filename = os.path.join(os.environ["HOMEDRIVE"], os.environ["HOMEPATH"], "Desktop", "test.csv")

with open(filename, "wb") as f:
    writer = csv.writer(f)
    writer.writerow(a)  # Or use writer.writerows([row] for row in a) for one per line

os.environ["HOMEDRIVE"] and os.environ["HOMEPATH"] would give your user's home folder, adding either Desktop or Documents would give you a suitable path. os.path.join() is used to safely join the various bits together with suitable separators giving you a filename such as:

C:\Users\Fred\Desktop\test.csv

This assumes you are using Python 2.x


If you are using Python 3.x, you would just need to modify how the file is opened for use with the CSV writer:

with open(filename, "w", newline="") as f:

Upvotes: 1

Related Questions