如何在文件路径中包含变量(Python)

时间:2015-09-15 09:57:32

标签: python

我目前正在Python3中编写一个小型网络聊天。我想要包含一个保存用户历史记录的功能。现在我的用户类包含一个名称变量,我想将历史文件保存在一个名为user的名称的文件夹中。

因此,例如它大致如此:

import os
import os.path

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

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

因此,在创建名为“exampleName”的文件夹之前,它返回“false”。 任何人都可以告诉我如何使这个工作? 非常感谢!

1 个答案:

答案 0 :(得分:1)

如果您对文件或目录名称使用 relative paths ,python将在当前工作目录$PWD变量中查找它们(或创建它们)在bash)。

如果你想让它们相对于当前的python文件,你可以使用(python 3.4)

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

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

或(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!')

如果您的History.txt文件位于python脚本下面的exampleName目录中。