Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File paths in Python in the form of string throw errors

I need to put a lot of filepaths in the form of strings in Python as part of my program. For example one of my directories is D:\ful_automate\dl. But Python recognizes some of the characters together as other characters and throws an error. In the example the error is IOError: [Errno 22] invalid mode ('wb') or filename: 'D:\x0cul_automate\\dl. It happens a lot for me and every time I need to change the directory name to one that may not be problematic.

like image 930
f.ashouri Avatar asked Dec 19 '12 15:12

f.ashouri


2 Answers

The \ character is used to form character escapes; \f has special meaning.

Use / or use raw string r'' instead. Alternatively, you could ensure that Python reads the backslash as a backslash by escaping it with an additional \.

r'D:\ful_automate\dl'
'D:\\ful_automate\\dl'
'D:/ful_automate/dl'

Demo to show the difference:

>>> 'D:\ful_automate\dl'
'D:\x0cul_automate\\dl'
>>> r'D:\ful_automate\dl'
'D:\\ful_automate\\dl'
like image 115
Martijn Pieters Avatar answered Oct 12 '22 15:10

Martijn Pieters


Use raw string instead of string ie use r'filepath' It fixes the problem off blacklash "\"

like image 37
user695580 Avatar answered Oct 12 '22 14:10

user695580