Python,尝试将CSV文件写入特定位置。

0 投票
1 回答
3649 浏览
提问于 2025-04-18 03:55

我想把一个文件写到指定的位置,所以我写了以下代码。

这个程序放在一个外部硬盘的文件夹里。我用了os.path来获取当前的路径(我想我这样做了……)

变量“fileName”是 = hello,变量“savePath”是 = data。

当我运行代码时,出现了以下错误……

IOError: [Errno 13] 权限被拒绝: 'data\hello_23-04-2014_13-37-55.csv'

我需要在尝试写入文件之前设置文件的权限吗?如果需要的话……该怎么做呢?

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)

1 个回答

2

当我尝试你这里的简化版本时,遇到了一个不同的错误(暂且不谈权限问题):

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

注意,当你这样做时:

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

...你正在创建一个目录,这个目录的名字既是你想要的路径(这很好),又是你想要创建的文件的名字。只需将路径传递给 makedirs(),然后在创建完这个目录后再在里面创建文件。

撰写回答