在 Python 3 中检查文件是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23459095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:00:39  来源:igfitidea点击:

check for file existence in Python 3

pythonpython-3.x

提问by krona

I would like to know how I could check to see if a file exist based on user input and if it does not, then i would like to create one.

我想知道如何根据用户输入检查文件是否存在,如果不存在,那么我想创建一个。

so I would have something like:

所以我会有类似的东西:

file_name = input('what is the file name? ')

then I would like to check to see if file name exist.

然后我想检查文件名是否存在。

If file name does exist, open file to write or read, if file name does not exist, create the file based on user input.

如果文件名存在,则打开文件进行写入或读取,如果文件名不存在,则根据用户输入创建文件。

I know the very basic about files but not how to use user input to check or create a file.

我知道关于文件的基本知识,但不知道如何使用用户输入来检查或创建文件。

回答by Amber

To do exactly what you asked:

要完全按照您的要求执行操作:

You're going to want to look at the os.path.isfile()function, and then the open()function (passing your variable as the argument).

您将要查看os.path.isfile()函数,然后查看open()函数(将变量作为参数传递)。



However, as noted by @LukasGraf, this is generally considered less than ideal because it introduces a race conditionif something else were you create the file in the time between when you check to see if it exists and when you go to open it.

但是,正如@LukasGraf 所指出的,这通常被认为不太理想,因为如果您在检查文件是否存在和打开文件之间的时间内创建了其他文件,它会引入竞争条件

Instead, the usual preferred method is to just try and open it, and catch the exception that's generated if you can't:

相反,通常的首选方法是尝试打开它,如果不能,则捕获生成的异常:

try:
    my_file = open(file_name)
except IOError:
    # file couldn't be opened, perhaps you need to create it

回答by saudi_Dev

You can use the os module:

您可以使用 os 模块:

Like this By os.path.isfile():

像这样通过 os.path.isfile():

import os.path
os.path.isfile(file_path)

Or Using os.path.exists():

或使用 os.path.exists():

if os.path.exists(file_name): print("I get the file >hubaa")

if the file doesn't exist :(return False)

如果文件不存在:(返回假)

if not os.path.exists(file_name):
      print("The File s% it's not created "%file_name)
      os.touch(file_name)
      print("The file s% has been Created ..."%file_name)

And you can write a simple code based on (try,Except):

并且您可以基于 (try,Except) 编写一个简单的代码:

try:
    my_file = open(file_name)
except IOError:
    os.touch(file_name)