I can't define a path in python. The backslash is seen as an continuation character

StackOverflow https://stackoverflow.com/questions/23477373

  •  15-07-2023
  •  | 
  •  

Question

I have an error in my code when i use a path. I'm trying to build in a bit of code to check if a file exists. In the previous exercises in my tutorial I could place the path within quotation marks but this path is not an argument to a function and won't accept this.

This is my code:

if os.C:\Users\\Casper\Desktop\headfirstpython\chapter 3.exits('sketch.txt')
data = open('sketch.txt')
for each_line in data:
    try:
        (role, line_spoken) = each_line.split(':', 1)
        print(role, end='')
        print(' said: ', end='')
        print(line_spoken, end='')
    except:
        pass

data.close()

I would really appreciate it if somebody could tell me what's wrong in my code.

Was it helpful?

Solution

This line is wrong on a few levels:

if os.C:\Users\\Casper\Desktop\headfirstpython\chapter 3.exits('sketch.txt')

You need to use:

if os.path.exists(r'C:\Users\Casper\Desktop\headfirstpython\chapter 3\sketch.txt'):

I changed three things:

  1. it's os.path.exists(path). The path isn't a valid function name. It's a string, passed as an argument.
  2. The backslashes need to be handled in one of three ways:
    • Escaped as two backslashes, which means one literal baclshash.
    • Use a forward slash (/). This does work even on Windows.
    • With r'string' notation, where the r tells Python to interpret it literally, without any characters escaped.
  3. You need to end your if statements with a colon (:). Further, you'll need to indent the code under it so Python knows what precisely to execute in the case the if is True.

As noted in the comments, be sure you've added import os to the top as well, or os will be undefined!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top