0

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.

3 Answers3

1

One option is to open the file before you change directories.

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

Another option is to save the original directory before changing, and use that to form an absolute path:

orig_dir = os.getcwd()
os.chdir(...)
...
with open(os.path.join(orig_dir, 'data.txt')) as data:
    print(data)
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

i think that is not possible, but i suggest that you if you plan to deploy this, make an error message wherein it tells the user to put the file that you want to open in the same directory as the python script

kalimdor18
  • 99
  • 13
0

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.