W
W
WGreed2021-12-27 12:22:26
Python
WGreed, 2021-12-27 12:22:26

How to change the opening path of a text file when you specify only the name?

When I open a text file for reading or writing, specifying only the file name, vs code opens the file along the path %UserProfile%\"file name"
How to open a file located in the same folder as the code file?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alan Gibizov, 2021-12-27
@phaggi

I usually use the pathlib library - there is Path ()
Then we do something like:

my_root = Path.cwd()  # cwd - current work dir
my_file = Path(“my_file_name.txt”)
my_file_full_path = my_root / myfile

Ps You can pathlib2, but there are nuances. For most cases, pathlib is sufficient.
Pps If you still need the %UserProfile% folder, use Path.home()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question