Skip to content Skip to sidebar Skip to footer

Os.path.isfile Isn't Working As Expected

I am trying to check if a file exists in Python using os.path.isfile(), but it is returning false although the file does exist. For example, when I type /Users/jordanbaron/Desktop/

Solution 1:

Windows 7, Python 2.7

If you're working with non ASCII letters, then you should decode your input properly. Maybe there are non ASCII letters in your file path that we cannot see. Try this code:

# -*- 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))

It works for path with Cyrillic letters:

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

Post a Comment for "Os.path.isfile Isn't Working As Expected"