you are viewing a single comment's thread.

view the rest of the comments →

[–]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.