Shad
Shad

Reputation: 203

Open file with relative path

I'm trying to open file in relative location:

import time, os
day=time.strftime("%Y%m%d")
month=time.strftime("%m")
filename=time.strftime("%Y%m%d")


logs_dir = os.path.dirname('C:\Users\user1\Desktop\folder\main\Logs') 
rel_path = '\'+month+'\'+filename+'.txt'
abs_file_path = os.path.join(script_dir, rel_path)
file = open(abs_file_path, 'r')

I couldn't get the second line right with variables and backslashes.

Upvotes: -1

Views: 711

Answers (2)

user2555451
user2555451

Reputation:

\u has special meaning in a Python string literal; it denotes a Unicode character. So does \f, which denotes a formfeed.

You will need to use a raw-string:

logs_dir = os.path.dirname(r'C:\Users\user1\Desktop\folder\main\Logs')

or forwardslashes:

logs_dir = os.path.dirname('C:/Users/user1/Desktop/folder/main/Logs')

in order to keep Python from interpreting them as such. You could also double every backslash:

logs_dir = os.path.dirname('C:\\Users\\user1\\Desktop\\folder\\main\\Logs')

but that is rather tedious.


Also, you need to double the backslash for every '\' since string literals cannot end in a single \. But this is not a very robust solution. A better approach for building paths is to use os.path.join:

rel_path = os.path.join('\\', month, filename + '.txt')

Then, you can replace every '\\' with os.sep as @helloV said in his answer. This will ensure that your code creates proper-looking paths on both Windows and *nix systems.

Upvotes: 2

helloV
helloV

Reputation: 52443

Use os.sep instead of '\', to avoid escaping issues.

Try:

abs_file_path = os.path.join(script_dir, month, filename) + '.txt'

Upvotes: 2

Related Questions