如何在python中检查路径/文件是否存在?

如何在python中检查路径/文件是否存在?,python,path,pickle,os.path,Python,Path,Pickle,Os.path,我有两个文件在目录abc test.py hello.txt 文件test.py: import os.path if os.path.exists('hello.txt'): print('yes') else: print('no') 当在同一目录中执行test.py时,正如我所期望的那样,输出为“yes” abc > python test.py output: yes 但当尝试从其他目录执行时 ~ > python ~/Desktop/abc/test.py

我有两个文件在目录
abc

test.py
hello.txt
文件
test.py

import os.path

if os.path.exists('hello.txt'):
  print('yes')
else:
  print('no')
当在同一目录中执行test.py时,正如我所期望的那样,输出为“yes”

abc > python test.py

output: yes
但当尝试从其他目录执行时

~ > python ~/Desktop/abc/test.py

output: no
如何纠正这个问题

# the real case
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)

当在目录abc中执行时,它可以工作,但从外部执行失败。

执行完整的路径,tilda

~
指定您“现在”所在的位置

要正确指定它,请执行完整路径。最简单的方法是进入“文件资源管理器”,右键单击文件,然后按“复制路径”。这将获得文件的完整路径,该路径可以在任何地方指定


请让我知道这是否有帮助

好吧,如果你不知道完整的路径,这对我来说要困难得多。我没有任何好的,像蟒蛇一样的想法去做那件事

要在整个PC中搜索文件,请使用subprocess模块并在linux上执行“查找”命令(您在linux上,对吗?),捕获输出,并询问您的文件是否存在:

import subprocess

file_name = "test.txt"

sp = subprocess.Popen(["find", '/', "-name", file_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = sp.communicate()

found = False
for line in output:
    if file_name.encode() in line:
        found = True

print("Found:", found)
注意:用您期望文件所在的父文件夹分隔搜索替换“/”


编辑:在windows上,虽然我无法测试它,但命令是:“dir/s/p hello.txt”,因此子进程调用如下:
sp=subprocess.Popen([“cmd”、“/c”、“dir”、“/s”、“/p”、“Links”]、stdout=subprocess.PIPE、stderr=subprocess.PIPE)

在这种情况下,您需要在遍历目录并读取内容后搜索文件。 您可以考虑<代码> OS.SCAN()/<代码>来遍历目录[Python 3.5 ]。

样本:

def find_file(path: str) -> str:
    for entry in scandir(path):
        if entry.is_file() and entry.name == 'token.pickle':
            return_path = f'{path}\{entry.name}'
            yield return_path
        elif entry.is_dir():
            yield from find_file(entry.path)

if __name__ == '__main__':
    for path in find_file('.'):
        with open(path, 'rb') as token:
            creds = pickle.load(token)

谢谢大家,我终于找到了解决办法,没想到会这么容易。。。。只需更改工作目录,瞧,我看到你已经发布了

无论如何,我想建议您,没有必要使用
os.chdir()
来实现此目的。实际上,只需这样做:

# the real case

path_to_your_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),"token.pickle")

if os.path.exists(path_to_your_file):
    with open(path_to_your_file, 'rb') as token:
        ...
附言。
如果你想知道,有几个很好的理由,主要的一个是首先给出一个完整的路径,如
D:/harsha/inputs/abc.txt
这两种方式都能正确执行。也许你需要给出绝对路径而不是相对路径。你想在固定位置查找pickle文件吗,或者你想在与python脚本相同的目录中查找它?@JohnGordon,我不想锁定文件位置,它在quiteOkay周围移动,那么程序应该如何知道在哪里查找它呢?Tilde的意思是“相对于主目录”,而不是“相对于我现在所在的位置”。我从终端运行它,因此,不可能每次都指定路径。完整路径不适合bcoz,有时需要更改目录。