chrylag
chrylag

Reputation: 11

How to include Variable in File Path (Python)

I am currently writing a small networkchat in Python3. I want to include a function to save the users history. Now my user class contains a variable for name and I want to save the history-file in a folder which has the name of the user as its name.

So for example it roughly looks like that:

import os
import os.path

class User:
    name = "exampleName"
    PATH = './exampleName/History.txt'

    def SaveHistory(self, message):
        isFileThere = os.path.exists(PATH)
        print(isFileThere)

So it is alwasy returning "false" until I create a folder called "exampleName". Can anybody tell me how to get this working? Thanks alot!

Upvotes: 1

Views: 8745

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46859

if you use relative paths for file or directory names python will look for them (or create them) in your current working directory (the $PWD variable in bash).

if you want to have them relative to the current python file, you can use (python 3.4)

from pathlib import Path
HERE = Path(__file__).parent.resolve()
PATH = HERE / 'exampleName/History.txt'

if PATH.exists():
    print('exists!')

or (python 2.7)

import os.path
HERE = os.path.abspath(os.path.dirname(__file__))
PATH = os.path.join(HERE, 'exampleName/History.txt')

if os.path.exists(PATH):
    print('exists!')

if your History.txt file lives in the exampleName directory below your python script.

Upvotes: 1

Related Questions