1

How can I change code on both computers into code that will universally recognise the same file (see bellow absolute paths) that is located differently. I don't want to move data and making the same repo locations on both computers because of storage issues on one PC, and I am importing data from my SD card.

PC1:

df = pd.read_csv("D:/data/text.txt")

PC2:

df = pd.read_csv("C:/Users/Uporabnik/Desktop/desktop/IJS/CESTEL/data/text.txt")
leskovecg
  • 83
  • 8

2 Answers2

2
from pathlib import Path


if running_on_pc_1():
  base_path = Path("D:")
else:
  base_path = Path("C:/Users/Uporabnik/Desktop/desktop/IJS/CESTEL")

file_path = base_path / "data/text.txt"

or...

from pathlib import Path
import os

base_path = Path(os.environ.get("BASE_FILE_PATH"))

file_path = base_path / "data/text.txt"

or...

import json
from pathlib import Path

config = json.loads("config.json")
base_path = Path(config["base_path"])
file_path = base_path / "data/text.txt"

and have a config file:

{
  "base_path": "C:/Users/Uporabnik/Desktop/desktop/IJS/CESTEL"
}

for each PC...:

{
  "base_path": "D:"
}
Tom McLean
  • 5,583
  • 1
  • 11
  • 36
1

You can use os.path for this. A quick example if your path id /data/text.txt You just need to specify the relative path from your script.

import os 

basedir = os.path.abspath(os.path.dirname(__file__))
generic_path= os.path.join(basedir, './data/text.txt')

Now the generic_path will work on every system !

Antoine Piron
  • 31
  • 1
  • 7
  • __file__ needs to be like this I think '__file__' – leskovecg Jul 18 '22 at 09:10
  • But still I dont get what I want. My output in this case is: 'c:\\Users\\lesko\\OneDrive\\Namizje\\laptop\\IJS\\./data/text.txt' but instead of this I want to get something like this: 'D:\data\text.txt' beacuse this data is on my SD card – leskovecg Jul 18 '22 at 09:12
  • The solution i gave you take the relative path from the python script (https://stackoverflow.com/questions/918154/relative-paths-in-python) that I often use. If the path is too specific you need to hard code them I think like @tom-maclean proposed – Antoine Piron Jul 19 '22 at 12:28