Tester P Tester P - 2 years ago 69
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

if folder name contains only numbers.

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

Is there any alternative way to do this?

Answer Source

Place a r character before the address string:

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

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

Another example:

>>> print "Test\nTest"
>>> print r"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"
>>> print r"\4534565"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download