Python os.path.isfile不是';他没有按预期工作
我试图使用Python os.path.isfile不是';他没有按预期工作,python,python-2.7,Python,Python 2.7,我试图使用os.path.isfile()检查Python中是否存在一个文件,但它返回false,尽管该文件确实存在。例如,当我键入/Users/jordanbaron/Desktop/hero bg.jpg时,这就是输出 Enter the directory to the ISO file (or just drag the file here): /Users/jordanbaron/Desktop/hero-bg.jpg /Users/jordanbaron/Desktop/hero-
os.path.isfile()
检查Python中是否存在一个文件,但它返回false,尽管该文件确实存在。例如,当我键入/Users/jordanbaron/Desktop/hero bg.jpg
时,这就是输出
Enter the directory to the ISO file (or just drag the file here): /Users/jordanbaron/Desktop/hero-bg.jpg
/Users/jordanbaron/Desktop/hero-bg.jpg
<type 'str'>
False
您发布的代码在以下情况下有效: 文件存在
/usr/bin/python2.7 /home/surest/github/tests/test.py
Enter the directory to the ISO file (or just drag the file here): /home/surest/Desktop/duties.odt
/home/surest/Desktop/duties.odt
<type 'str'>
True
Process finished with exit code 0
/usr/bin/python2.7/home/surest/github/tests/test.py
输入ISO文件的目录(或将文件拖到此处):/home/surest/Desktop/durtions.odt
/主页/surest/Desktop/ductions.odt
真的
进程已完成,退出代码为0
键入文件名/路径
/usr/bin/python2.7 /home/surest/github/tests/test.py
Enter the directory to the ISO file (or just drag the file here): /home/surest/Desktop/meesa-typoed.odt
/home/surest/Desktop/meesa-typoed.odt
<type 'str'>
False
Process finished with exit code 0
/usr/bin/python2.7/home/surest/github/tests/test.py
输入ISO文件的目录(或将文件拖到此处):/home/surest/Desktop/meesa-typed.odt
/home/surest/Desktop/meesa-typed.odt
假的
进程已完成,退出代码为0
Windows7、Python 2.7
如果使用非ASCII字母,则应正确解码输入。可能您的文件路径中有我们看不到的非ASCII字母。请尝试以下代码:
# -*- coding: utf-8 -*-
import os, sys, locale
filename = raw_input("Enter filepath: ").decode(sys.stdin.encoding or locale.getpreferredencoding(True))
print(filename)
print(type(filename))
print(os.path.exists(filename))
它适用于带有西里尔字母的路径:
C:\Projects>c:\Python27\python.exe filepath.py
Enter filepath: c:\Projects\темп\jordanbaron\Рабочий стол\hero-bg.jpg
c:\Projects\темп\jordanbaron\Рабочий стол\hero-bg.jpg
<type 'unicode'>
True
C:\Projects>C:\Python27\python.exe filepath.py
输入文件路径:c:\Projects\ММП\jordanbaron\Пббчббббб\hero-bg.jpg
c:\Projects\ММП\jordanbaron\Мбчббчббббббббб
真的
“但尽管文件确实存在,但返回的却是true。”呃,您是否希望os.path.isfile
即使文件确实存在也返回False
?您输入了目录名或文件名?@Shiping:os.path.isfile
检查正常文件是正确的。当然,如果他们想要文件或目录,存在
是一个很好的初始测试。也就是说,我们不知道用户正在输入什么,或者文件系统是什么样子,所以这很难回答(这可能是输入或文件系统布局中的错误)。我不理解你的问题<当目标存在时,code>os.path.isfile返回True
。这正是预期的行为。。。(至少在linux上)恐怕该文件不存在,或者您键入了错误的名称。您能运行命令“ls-l/Users/jordanbaron/Desktop/hero bg.jpg”吗?OP在Mac系统上。您必须这样做的原因是因为temp
是一个相对路径。如果路径的前缀是“\”,那么它必须一直到驱动器路径C
@suresttexas——是的,我知道。但是绝对路径对我来说在Python2.7上也不起作用。自从我在windows上使用Python已有几年了,但是我认为你必须做一些事情,比如c\windows\temp\jordan…
或者mabe justc:\windows\temp…
你基本上只是在使用相对路径,因为你不知道正确的绝对路径(它不是/temp/jordanbaron/Desktop/hero bg.jpg
)。
C:\Projects>c:\Python27\python.exe filepath.py
Enter filepath: c:\Projects\темп\jordanbaron\Рабочий стол\hero-bg.jpg
c:\Projects\темп\jordanbaron\Рабочий стол\hero-bg.jpg
<type 'unicode'>
True