python:访问“cousin”.txt文件

时间:2017-03-26 23:51:53

标签: python directory

我有一个像这样的目录结构:

project
  gamelib
    game.py
  levels
    level1.txt

我需要game.py才能访问level1.txt。

with open(path, "r") as f:
  ...

如何访问level1.txt的路径?

1 个答案:

答案 0 :(得分:0)

要么给它完整的路径

with open("/usr/yourUser/../project/levels/level1.txt", "r") as f:

或相对路径(这认为您的脚本 game.py 位于 ./ project 级别)

with open("./levels/level1.txt", "r") as f:

在您的示例中,您必须返回

with open("../levels/level1.txt", "r") as f: