1

I am trying to build a bot which gives a random answer from CSV file. Piece of code I have problem with:

def get_data(lounaslista):
    with open('C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv', 'r') as f:
        r = csv.reader(f)
        data = [row for row in r]
    return data

Error I'm getting:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

I tried solutions from following post.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
s4ltyfish
  • 21
  • 1
  • 4

2 Answers2

2

Use double slash instead of simple slash in path.

def get_data(lounaslista):
    with open('C:\\Users\\p7l1n\\Desktop\\lounasbotti\\lounaslista.csv', 'r') as f:
        r = csv.reader(f)
        data = [row for row in r]
    return data

Example with simple variable:

a = 'C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv'
# SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

# With double slash:
a = 'C:\\Users\\p7l1n\\Desktop\\lounasbotti\\lounaslista.csv'
print(a)  # C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv

# Or use raw string:
a = r'C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv'
print(a)  # C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv
ErnestBidouille
  • 1,071
  • 4
  • 16
1

The backslash character in strings is used as an escape character. For example \n is a newline, \" and \' can be used to insert " and ' into string literals without terminating those literals. You can also write \U00000000 to insert a character with that code point (instead of 00000000 you can have any hexadecimal number).

To insert a literal backslash, you have to escape the backslash, like so: \\

For Windows file paths, this gets a bit tedious, so there is an alternative: raw string literals, like so: r'C:\Users\p7l1n\Desktop\lounasbotti\lounaslista.csv'. This disables escape sequences.

A third option is to use forward slashes instead: 'C:/Users/p7l1n/Desktop/lounasbotti/lounaslista.csv'. Windows generally accepts forward slashes as an alternative path separator.

Jasmijn
  • 9,370
  • 2
  • 29
  • 43