0

pathlib.Path.cwd() returns a different value depending on what computer I use (two Windows PCs - one at work, one at home).

Project structure (see https://github.com/jonathanchukinas/file_read_exercise.git)

  • file_read_exercise/
    • bin/
      • init.py
      • read_excel_file.py
    • data/
      • init.y
      • my_data.xlsx
    • init.py
    • main.py

main.py and read_excel_file.py both contain: from pathlib import Path print(Path.cwd()) At work, each python file returns the absolute path to the top-level directory. At home, each python file returns the absolute path to its own directory.

I've been through the documentation and I've googled and searched stack overflow and can't find an answer to this question:

How does cwd() work so that I can better predicts its results?

2 Answers2

6

It returns the current working directory, that is, the directory from where you run the script.

Example:

  1. stradivari:~/Desktop/file_read_exercise$ python main.py

    Should return the path for ~/Desktop/file_read_exercise:

    cwd, when called from main, returns: /home/stradivari/Desktop/file_read_exercise
    
  2. stradivari:~/Desktop$ python ./file_read_exercise/main.py

    Should return the path to my Desktop:

    cwd, when called from main, returns: /home/stradivari/Desktop
    
Stradivari
  • 2,626
  • 1
  • 9
  • 21
0

You can use this function to establish path without hardcode it:

import pathlib

def find_path_to_file(file_name):
    globa_path = pathlib.Path.home()
    for path in sorted(globa_path.rglob('*')):
            if str(file_name) in str(path):
                return str(path)

Also you can replace home() on cwd() if you put this function in the same folder as searching file, or try with parent argument:

def find_path_to_file(file_name):
    global_path = pathlib.Path.cwd()
    for path in sorted(global_path.rglob('*')):
            if str(file_name) in str(path):
                return str(path)
            else:
                for path in sorted(global_path.parent.parent.rglob('*')):
                    if str(file_name) in str(path):
                        return str(path)
Bartol
  • 83
  • 1
  • 9