Pregunta

I am trying to write a file to a specific location, to do this I wrote the following code.

The program is in a folder on an external HDD. I have used the os.path to get the current path (I think..)

the "fileName" var is = hello the "savePath" var is = data

When I run the code I get the following error...

IOError: [Errno 13] Permission denied: 'data\hello_23-04-2014_13-37-55.csv'

Do I need to set permissions for the file before I try to write to it? If so.. how do you do this>?

def writeData(fileName, savePath, data):
    # Create a filename
    thisdate = time.strftime("%d-%m-%Y")
    thistime = time.strftime("%H-%M-%S")
    name = fileName + "_" + thisdate + "_" + thistime + ".csv"

    # Create the complete filename including the absolute path 
    completeName = os.path.join(savePath, name)

    # Check if directory exists
    if not os.path.exists(completeName):
        os.makedirs(completeName)

    # Write the data to a file
    theFile = open(completeName, 'wb')
    writer = csv.writer(theFile, quoting=csv.QUOTE_ALL)
    writer.writerows(data)
¿Fue útil?

Solución

I get a different error (putting permission issues aside) when I try a stripped down version of what you're doing here:

>>> import os
>>> path = "foo/bar/file.txt"
>>> os.makedirs(path)
>>> with open(path, "w") as f:
...    f.write("HOWDY!")
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 21] Is a directory: 'foo/bar/file.txt'

Note that when you do this:

# Check if directory exists
if not os.path.exists(completeName):
    os.makedirs(completeName)

...you're creating a directory that has a name that's both the path you want (good) and the name of the file you're trying to create. Pass the pathname only to makedirs() and then create the file inside that directory when you've done that.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top