Search code examples
pythonpython-3.xiochdir

Access a file even if the cwd has changed


The below code works perfectly:

with open('data.txt') as data:
    print(data)

But if I changed the CWD using os.chdir, It won't work

Is there a way in which I can access the file while still being able to change the CWD?

Note: The way the CWD will change will depend on how the user uses it.


Solution

  • thank you for your answers

    But I think I have got it myself!

    Before I call the os.chdir function, I can do,

    from pathlib import Path
    datafile = Path('data.txt').absolute()
    

    Then I will get the absolute path in any computer that I run this in.