1

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!

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.