os.path.isfile没有按预期工作

时间:2017-04-24 23:06:55

标签: 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-bg.jpg 
<type 'str'>
False

文件确实存在。

file

为什么会这样?

filename = raw_input("Enter the directory to the ISO file (or just drag the file here): ")
print(filename)
print(type(filename))
print(os.path.isfile(filename))

2 个答案:

答案 0 :(得分:2)

您发布的代码有效:

文件存在

/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
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

答案 1 :(得分:0)

Windows 7,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
相关问题