Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: os.path.isfile won't recognise files beginning with a number

So, I'm trying to incorporate os.path.isfile or os.path.exists into my code with success in finding certain regular files(pdf,png) when searching for filenames that begin with a letter.

The file naming standard that I'm using (and can't change due to the user) starts with a number and subsequently can't be found using the same method. Is there a way that I can make these files discoverable by .isfile or .exists?

The files I'm searching for are .txt files.

    os.path.isfile("D:\Users\spx9gs\Project Work\Data\21022013AA.txt")

    os.path.isfile("D:\Users\spx9gs\Project Work\Data\AA21022013.txt")

Returns:

False

True

like image 241
user2111029 Avatar asked Feb 26 '13 11:02

user2111029


1 Answers

You need to use raw strings, or escape your backslashes. In the filename:

"D:\Users\spx9gs\Project Work\Data\21022013AA.txt"

the \210 will be interpreted as an octal escape code so you won't get the correct filename.

Either of these will work:

r"D:\Users\spx9gs\Project Work\Data\21022013AA.txt"
"D:\\Users\\spx9gs\\Project Work\\Data\\21022013AA.txt"
like image 59
interjay Avatar answered Sep 26 '22 23:09

interjay