'open a file and read data from file in python

import numpy as np
data = np.loadtxt(os.path.join('\Users\timot\Downloads\LAB EXERCISE 1-20220331\Data', 'ex1data1.txt'), delimiter=',')
X, y = data[:, 0], data[:, 1]

This is my codes that try to open a file in the directory.

This is the error I got:

 Input In [1]
    data = np.loadtxt(os.path.join('\Users\timot\Downloads\LAB EXERCISE 1-20220331\Data', 'ex1data1.txt'), delimiter=',')
                                                                                        ^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \UXXXXXXXX escape

How should I fix this code as I am new to python?



Solution 1:[1]

'\Users\timot\Downloads\LAB EXERCISE 1-20220331\Data'

Do you know how Python reads this? An example is \t, that is interpreted as a tab, or \n which is interpreted as a newline. Try to use a raw-string instead:

r'\Users\timot\Downloads\LAB EXERCISE 1-20220331\Data' # This works properly

or to escape the \ backslashes

'\\Users\\timot\\Downloads\\LAB EXERCISE 1-20220331\\Data'

Solution 2:[2]

slash() is an escape character in python.

Use a raw string (prefixed with the letter r"") for strings that contain back slash () to ignore these characters.

For example, 

r"\Users\timot\..."

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FLAK-ZOSO
Solution 2 Ade_1