简体   繁体   English

Python 创建目录错误 当文件已存在时无法创建文件

[英]Python create directory error Cannot create a file when that file already exists

I'm trying to create directories only if they don't exist using Python.我仅在使用 Python 时才尝试创建目录。

If the directory doesn't exist the script runs fine.如果目录不存在,则脚本运行良好。 But if it's already there I get an error that says:但是,如果它已经存在,我会收到一条错误消息:

An error has occurred: [WinError 183] Cannot create a file when that file already exists: '..\\..\\source_files\\aws_accounts_list'
Traceback (most recent call last):
  File ".\aws_ec2_list_instances.py", line 781, in <module>
    main()
  File ".\aws_ec2_list_instances.py", line 654, in main
    mongo_export_to_file(interactive, aws_account, aws_account_number)
  File "C:\Users\tdun0002\OneDrive - Synchronoss Technologies\Desktop\important_folders\Jokefire\git\jf_cloud_scripts\aws_scripts\python\aws_tools\ec2_mongo.py", line 292, in mongo_export_to_file
    create_directories()
  File "C:\Users\tdun0002\OneDrive - Synchronoss Technologies\Desktop\important_folders\Jokefire\git\jf_cloud_scripts\aws_scripts\python\aws_tools\ec2_mongo.py", line 117, in create_directories
    os.makedirs(source_files_path)
  File "C:\Users\tdun0002\AppData\Local\Programs\Python\Python38-32\lib\os.py", line 223, in makedirs
    mkdir(name, mode)
FileExistsError: [WinError 183] Cannot create a file when that file already exists: '..\\..\\source_files\\aws_accounts_list'

This is my code:这是我的代码:

def create_directories():
    ## Set source and output file directories
    source_files_path = os.path.join('..', '..', 'source_files', 'aws_accounts_list')

    # Create output files directory
    try:
        os.makedirs(source_files_path)
    except OSError as e:
        print(f"An error has occurred: {e}")
        raise

I want the exception to allow the script to continue if it encounters an error like this.如果遇到这样的错误,我希望异常允许脚本继续。 How can I do that?我怎样才能做到这一点?

From Python 3.4, with pathlib this becomes quite an easy task using Path.mkdir :从 Python 3.4 开始,使用pathlib使用Path.mkdir变得非常容易:

from pathlib import Path

def create_directories():
    ## Set source and output file directories
    source_files_path = Path('..', '..', 'source_files', 'aws_accounts_list')

    # Create output files directory
    source_files_oath.mkdir(parents=True, exist_ok=True)

If you insist on os , then makedirs has another argument since Python 3.2 - exist_ok , which is:如果您坚持使用os ,那么makedirs自 Python 3.2 - exist_ok以来还有另一个论点,即:

If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists.如果exists_okFalse (默认值),如果目标目录已经存在,则会引发FileExistsError

So just change to:所以只需更改为:

os.makedirs(source_files_path, exist_ok=True)

Just don't reraise the error只是不要重新提出错误

# Create output files directory
try:
    os.makedirs(source_files_path)
except OSError as e:
    print(f"An error has occurred. Continuing anyways: {e}")

But we don't actually want to skip all OS errors, only if the file doesn't exist, so a better solution would be:但我们实际上并不想跳过所有操作系统错误,只有当文件不存在时,所以更好的解决方案是:

# Create output files directory
try:
    os.makedirs(source_files_path)
except FileExistsError as e:
    print('File already exists')
    return False
except OSError as e:
    print(f"An error has occurred: {e}")
    raise

As Tomerikoo suggested, You can also use os.path.exists正如Tomerikoo建议的那样,您也可以使用os.path.exists

import os

if not os.path.exists(source_files_path):
    try:
        os.makedirs(source_files_path)
    except OSError as e:
        print(f"An error has occurred: {e}")
        raise

I leave this below as reference, as it may be suited for other situations similar.我将其保留在下面作为参考,因为它可能适用于其他类似的情况。

You can make a check with os.path.isdir in case of a Directory:如果是目录,您可以使用os.path.isdir进行检查:

import os

if not os.path.isdir(source_files_path):
    try:
        os.makedirs(source_files_path)
    except OSError as e:
        print(f"An error has occurred: {e}")
        raise

Or, you can use os.path.isfile in case of a file path:或者,您可以在文件路径的情况下使用os.path.isfile

import os

if not os.path.isfile(source_files_path):
    try:
        os.makedirs(source_files_path)
    except OSError as e:
        print(f"An error has occurred: {e}")
        raise

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Python观察到该文件已存在时无法创建文件 - Cannot create a file when that file already exists error observed using Python Winerror 183 文件已存在时无法创建文件 - Winerror 183 Cannot create a file when that file already exists 重命名txt文件。 编辑版本:[错误183]该文件已存在时无法创建该文件 - Rename txt file. Edited version: [Error 183] Cannot create a file when that file already exists Google App Engine:“文件已经存在时无法创建” - Google App Engine: “Cannot create a file when that file already exists” FileExistsError:[WinError 183] 当文件已存在时无法创建文件 - FileExistsError: [WinError 183] Cannot create a file when that file already exists python os.rename“”在该文件已存在时无法创建该文件 - python os.rename “”cannot create a file when that file already exists 为什么我收到错误消息:“FileExistsError: [WinError 183] 当文件已存在时无法创建文件”? - Why am I getting the error: "FileExistsError: [WinError 183] Cannot create a file when that file already exists"? 创建目录然后在Python中打开其中的文件时出错,但如果目录已存在则没有错误 - Error when creating directory and then opening a file within it in Python, but no error if directory already exists 如何解决 FileExistsError: [WinError 183] 当文件已经存在时无法创建文件? - How to resolve FileExistsError: [WinError 183] Cannot create a file when that file already exists? os.rename 无法创建已存在的文件 - os.rename cannot create a file that already exists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM