Tester P Tester P - 11 months ago 33
Python Question

Unable to search for directory using isdir when folder name had on numeric using Python

I am creating folder after checking non-existence of folder with same name. However I am unable to check for the folder using

isdir
if folder name contains only numbers.

>>> print(os.path.isdir('D:\Git_File\IAutomation\dir4534565'))
True
>>> print(os.path.isdir('D:\Git_File\IAutomation\4534565'))
False


Is there any alternative way to do this?

Answer

Place a r character before the address string:

>>> os.path.isdir("D:\IAutomation\4534565")
False
>>> os.path.isdir(r"D:\IAutomation\4534565")
True
>>> 

This r means raw. The interpreter won't consider any escape character replacement in the string.

Another example:

>>> print "Test\nTest"
Test
Test
>>> print r"Test\nTest"
Test\nTest
>>>

As you see above, in the second example, as I put a r before the string, the interpreter didn't replaced \n with a break line in the output. It consider whole the characters as raw characters.

For your case in the question, \453 will replaced with + by interpreter and then the search will happen:

>>> print "\4534565"
+4565
>>> print r"\4534565"
\4534565
>>>