检查Python 3中是否存在文件

kro*_*ona 12 python python-3.x

我想知道如何检查是否存在基于用户输入的文件,如果不存在,那么我想创建一个.

所以我会有类似的东西:

file_name = input('what is the file name? ')
Run Code Online (Sandbox Code Playgroud)

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

如果文件名确实存在,则打开要写入或读取的文件,如果文件名不存在,则根据用户输入创建文件.

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

sau*_*Dev 26

你可以使用os模块:

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

import os.path
os.path.isfile(file_path)
Run Code Online (Sandbox Code Playgroud)

或者使用os.path.exists():

if os.path.exists(file_name): print("I get the file >hubaa")
Run Code Online (Sandbox Code Playgroud)

如果文件不存在:(返回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)
Run Code Online (Sandbox Code Playgroud)

你可以编写一个简单的代码(try,Except):

try:
    my_file = open(file_name)
except IOError:
    os.touch(file_name)
Run Code Online (Sandbox Code Playgroud)


Amb*_*ber 5

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

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


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

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

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

  • 这正是你不应该做的,因为这引入了[竞争条件](http://stackoverflow.com/questions/14574518/how-does-using-the-try-statement-avoid-a-race -健康)状况)。 (2认同)