我在目录np.histogram
中有两个文件
abc
文件test.py
hello.txt
:
test.py
在同一目录中执行test.py时,输出:'是'
import os.path
if os.path.exists('hello.txt'):
print('yes')
else:
print('no')
但是当尝试从其他目录执行时
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)
中执行时有效,但在外部表单失败。
答案 0 :(得分:0)
做一个完整的路径,tilda
~
指定您现在所在的位置
要正确指定它,请执行完整路径。最简单的方法是转到文件资源管理器,右键单击文件,然后按复制路径。这应该为您提供了可以在任何地方指定的文件的完整路径。
请告诉我这是否有帮助!
答案 1 :(得分:0)
好吧,如果您不知道完整的路径,恕我直言,这要困难得多。我没有什么好主意,pythonic做到这一点!
要在整个PC上搜索文件,请使用子处理模块并在linux上执行“ find”命令(您在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)
答案 2 :(得分:0)
在这种情况下,您需要在遍历目录并读取内容之后搜索文件。
您可能会考虑os.scandir()
遍历目录[python 3.5]。
https://www.python.org/dev/peps/pep-0471/
示例:
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)
答案 3 :(得分:0)
谢谢,每个人,终于我找到了解决方案,从来没有想到这会很简单...。只需更改工作目录并确认其工作??
nnoremap K K<C-w>L
nnoremap <A-h> :set hls!<cr>
nnoremap / :set hlsearch<cr>/
nnoremap <A-j> 10j
nnoremap <A-k> 10k
nnoremap <A-w> W
nnoremap <A-b> B
nnoremap <A-v> V
nnoremap <A-m> '
nnoremap <A-p> "+p
nnoremap <A-y> "+y
nnoremap <A-4> $
nnoremap <A-3> 0
nnoremap Y y$
vnoremap <A-h> :set hls!<cr>
vnoremap / :set hlsearch<cr>/
vnoremap <A-j> 10j
vnoremap <A-k> 10k
vnoremap <A-w> W
vnoremap <A-b> B
vnoremap <A-v> V
vnoremap <A-m> '
vnoremap <A-p> "+p
vnoremap <A-y> "+y
vnoremap <A-4> $
vnoremap <A-3> 0
答案 4 :(得分:0)
我看到您已经发布了answer to your own question here
无论如何,我想建议您实际上不需要使用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:
...
P.S。
如果您想知道,prefer using os.path.join()
over manual string concatenation有几个很好的理由,首先是makes your coding platform independent