Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.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
有没有办法测试并给出一个True/False语句来查看文件是否存在,Python_Python_File - Fatal编程技术网

有没有办法测试并给出一个True/False语句来查看文件是否存在,Python

有没有办法测试并给出一个True/False语句来查看文件是否存在,Python,python,file,Python,File,我试图在代码行中检查目录中是否存在名为text1.txt的文件。如果它存在,它将继续运行程序,如果它不存在,它将执行其他操作。您可以使用pathlib2库 from pathlib2 import Path if (Path(".") / <YOUR_FILE_NAME_.txt>).exists(): do your stuff here 假设您从目录运行python代码,您可以使用os内置模块。请点击此处: 基本上,您可以尝试类似的方法,请记住,如果包含该文件的目录不是c

我试图在代码行中检查目录中是否存在名为text1.txt的文件。如果它存在,它将继续运行程序,如果它不存在,它将执行其他操作。

您可以使用pathlib2库

from pathlib2 import Path

if (Path(".") / <YOUR_FILE_NAME_.txt>).exists():
  do your stuff here

假设您从目录运行python代码,您可以使用os内置模块。请点击此处:

基本上,您可以尝试类似的方法,请记住,如果包含该文件的目录不是cwd,则需要提供该文件的完整路径

import os
os.path.exists('<filename>')

如果您已经在使用pathlib,您可以只使用路径上的.exists。

考虑一下您看到的os.Path.exists?