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

问题描述 投票:1回答:3

我在abc目录中有两个文件

test.py
hello.txt

test.py

import os.path

if os.path.exists('hello.txt'):
  print('yes')
else:
  print('no')

在同一目录中执行test.py时,输出:'是'

abc > python test.py

但是尝试从其他目录执行时

~ > 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)

它在目录中的execuintg起作用但在外部的表单失败时起作用>

我在abc目录中有两个文件test.py hello.txt test.py如果os.path.exists('hello.txt')导入os.path:print('yes')否则:print('no')在同一目录中执行test.py时,输出:'yes'...

python path pickle os.path
3个回答
0
投票

执行完整的路径,tilda


0
投票

好吧,如果您不知道完整的路径,恕我直言,这要困难得多。我没有什么好主意,pythonic可以做到这一点!


0
投票

在这种情况下,您需要搜索文件。os.scandir()是您所需要的https://www.python.org/dev/peps/pep-0471/

© www.soinside.com 2019 - 2024. All rights reserved.