Home > Software design >  Finding universal path that will work on both computers while reading the same data
Finding universal path that will work on both computers while reading the same data

Time:07-18

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")

CodePudding user response:

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:"
}

CodePudding user response:

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 !

  • Related