Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Can';t在我创建的目录中保存文件_Python_Python 3.x_File_Path - Fatal编程技术网

Python Can';t在我创建的目录中保存文件

Python Can';t在我创建的目录中保存文件,python,python-3.x,file,path,Python,Python 3.x,File,Path,我使用以下代码创建了一个文件夹: def _infrastructure(self): lib = "data" try: os.makedirs(lib) except OSError as e: if e.errno != errno.EXIST: raise 我想保存一个使用以下代码创建的文件: def save(self, dic): filename = "file.csv"

我使用以下代码创建了一个文件夹:

def _infrastructure(self):
    lib = "data"
    try:
        os.makedirs(lib)
    except OSError as e:
        if e.errno != errno.EXIST:
            raise
我想保存一个使用以下代码创建的文件:

def save(self, dic):
    filename = "file.csv"           
    my_path = "data"
    filepath = os.path.join(os.path.expanduser('~'), my_path, filename)
    self.curr = csv.writer(open(filepath, "w"))            

    for key, val in self.dic.items():
        self.curr.writerow([key, val])
我要做的是将我创建的文件保存在我也创建的文件夹中,这里的问题似乎在for循环中,因为我的所有变量都会获取参数

提出的例外情况是:

Traceback (most recent call last): self.curr = csv.writer(open(filepath, 
    "w")) FileNotFoundError: [Errno 2] No such file or directory: 
    'C:\\Users\\user\\data\\file.csv'

查看回溯中显示的行。这是打开文件的那一行。它在进入for循环之前执行。换句话说,在异常发生之前甚至没有到达for循环。如果从调用
os.makedirs
前后删除
try..except
,您可能会获得额外的调试信息。可能存在某个操作系统错误,
e.errno==errno.EXIST
,而
try..except
正在默默地吞没。
\u基础设施
希望您的工作目录是
os.path.expanduser(“~”)
-真的是这样吗?您可以将
print(os.getcwd())
放入其中,然后再次测试。这是打开文件的那一行。它在进入for循环之前执行。换句话说,在异常发生之前甚至没有到达for循环。如果从调用
os.makedirs
前后删除
try..except
,您可能会获得额外的调试信息。可能存在某个操作系统错误,
e.errno==errno.EXIST
,而
try..except
正在默默地吞没。
\u基础设施
希望您的工作目录是
os.path.expanduser(“~”)
-真的是这样吗?您可以将
print(os.getcwd())
放入其中,然后再次测试。