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.

5
  • 1
    Your imput csv isn't in (correct) unicode. Either it's in another encoding, or you need to fix the mojibake. In either case this has nothing to do with python. Commented Oct 26, 2022 at 11:36
  • The linked post is orthogonal to the issue here (csv encoding). Commented Oct 26, 2022 at 11:36
  • Hi, welcome to Stack Overflow! What encoding is your text file? Can you try reading it with a different encoding? Commented Oct 26, 2022 at 11:38
  • Encoding does not matter here, error is in the path string Commented Oct 26, 2022 at 11:43
  • Does this answer your question? Windows path in Python Commented Oct 26, 2022 at 13:04

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.