Python SyntaxError occurred when you are trying to access a path with normal String. As you know ‘/’ is escape character in Python that’s having different meaning by adding with different characters for example ‘\n’ is use for one line , ‘\t’ use for tab.
This error is considered as Python SyntaxError because unicode forward slash (\) is not allow in path.
In further section of topic you will learn how to handle this problem in Python while writing path of file to access it.
See Also:
Example of Python SyntaxError of Unicode Error
Lets take below example to read CSV file in Windows operating system.
import csv
with open('C:\Users\saurabh.gupta\Desktop\Python Example\input.csv','r') as csvfile:
reader=csv.reader(csvfile)
for record in reader:
print(record)
If you notice the above code is having path for windows file system to access input.csv. In windows path mentioned by using forward slash (\) while in Python programming forward slash(\) is use for handling unicode characters. That’s why when you execute the above program will throw below exception.
Output
File "C:/Users/saurabh.gupta14/Desktop/Python Example/ReadingCSV.py", line 2
with open('C:\Users\saurabh.gupta\Desktop\Python Example\input.csv','r') as csvfile:
Solution
The above error is occurred because of handling forward slash(\) as normal string. To handle such problem in Python , there are couple of solutions:
1: Just put r in path before your normal string it converts normal string to raw string:
with open(r'C:\Users\saurabh.gupta\Desktop\Python Example\input.csv','r')
2: Use back slash (/) instated of forward slash(\)
with open('C:/Users/saurabh.gupta/Desktop/Python Example/input.csv','r')
3: Use double forward slash (\\) instead of forward slash(\) because in Python the unicode double forward value convert in string as forward slash(\)’
with open('C:\\Users\\saurabh.gupta\\Desktop\\Python Example\\input.csv','r')
If this solution help you , Please like and write in comment section or any other way you know to handle this issue write in comment so that help others.
Related Posts
Your Feedback Motivate Us
If our FacingIssuesOnIT Experts solutions guide you to resolve your issues and improve your knowledge. Please share your comments, like and subscribe to get notifications for our posts.
Happy Learning !!!
You must log in to post a comment.