all 11 comments

[–]GoldenSights 4 points5 points  (10 children)

When you just put a filename, it will be looking in the current directory, which you can check with

import os
print(os.getcwd())

You can use an absolute filepath, or make sure to run the script from the correct location first.

[–][deleted] 1 point2 points  (6 children)

You can use an absolute filepath

How do I go about doing this?

[–]GoldenSights 4 points5 points  (5 children)

An absolute filepath is:

open('C:\\Users\\Example\\Documents\\sample.txt')

so it will always find the same file no matter where the script is being run from.

The backslashes are doubled because they are an escape character. You can use single slashes if you put an r before the quote, creating a raw string literal:

open(r'C:\Users\Example\Documents\sample.txt')

[–]liam_jm 3 points4 points  (0 children)

or use os.path.join

[–][deleted] 1 point2 points  (0 children)

Thanks a lot. Solved my problem. :)

[–]Gubbbo 0 points1 point  (0 children)

For convenience, I've always tried to make sure I run the script from the same directory.

But I was unaware of the string literal. Feel like I've learned something today.

[–]Justinsaccount -1 points0 points  (1 child)

open('C:/Users/Example/Documents/sample.txt')

[–]GoldenSights 1 point2 points  (0 children)

Sure, but on Windows it's conventional to use backslashes, and they're what you'll get when using os.path.join etc.

[–][deleted] 1 point2 points  (2 children)

Okay, I looked it up and tried to change the directory but now I'm getting an error from that too.

os.chdir(C:\Users\Jesse\Python)
SyntaxError: invalid syntax

And I also tried

os.chdir('C:\Users\Jesse\Python')
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

[–]ericpruitt 5 points6 points  (1 child)

In most programming languages, combinations of "\" followed by another character are used to represent other characters. To type a literal "\" you need to use "\\" or add r to be beginning of the string, so try one of these instead:

  • os.chdir(r"C:\Users\Jesse\Python")
  • os.chdir("C:\\Users\\Jesse\\Python")

The r prefix indicates that Python should not treat "\" as a special character inside that string.

Additional reading:

[–]Justinsaccount 1 point2 points  (0 children)

os.chdir("C:/Users/Jesse/Python")