有没有一种方法可以在两个不同的项目中共享文件而不使用绝对路径?

时间:2019-10-01 22:16:45

标签: python

在python中,我有一个文本文件,需要在ProjectB和ProjectA中共享。假设我将“ data.txt”放入ProjectB。并且ProjectB和ProjectA在同一父目录下,即:

ProjectA
  test_data.py

ProjectB
   data.txt

现在,我要在ProjectA中打开“ data.txt”。有没有办法从ProjectA到达它而不使用绝对路径?

1 个答案:

答案 0 :(得分:0)

只需在ProjectA中创建一个python文件(将其命名为open_data.py),然后将以下行放入其中,然后运行它即可。

with open('../ProjectB/data.txt', 'r') as foo:
    data = foo.read()
    print(data)  

这是您所描述的文件夹树:

Parent_Folder
├── ProjectA
│   └── open_data.py
└── ProjectB
    └── data.txt

从ProjectA运行open_data.py之后,您将获得ProjectB中存在的内容data.txt

~$ cd Parent_Folder/ProjectA/
~/Parent_Folder/ProjectA$ python3 open_data.py 
This is data.txt from ProjectB