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
Solution 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')
ifos.path.exists(PATH):
print('exists!')
if your History.txt
file lives in the exampleName
directory below your python script.
Post a Comment for "How To Include Variable In File Path (python)"