0

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!

chrylag
  • 1
  • 1
  • 1
  • related http://stackoverflow.com/questions/273192/in-python-check-if-a-directory-exists-and-create-it-if-necessary – gokul_uf Sep 15 '15 at 10:11

1 Answers1

1

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.

hiro protagonist
  • 36,147
  • 12
  • 68
  • 86