wind
wind

Reputation: 2441

Files not being saved in the right directory in Python

I have 2 files:

  1. First file test1.py:

    from dir2.test2 import func2
    
    def func1():
       with open("test1.txt", "w") as f:
           f.write("some text")
    
    func1()
    func2()
    
  2. Second file test2.py:

    def func2():
        with open("test2.txt", "w") as f:
            f.write("some text")
    

And my directory structure looks like this before running test1.py:

dir1
 |
 - test1.py
 |
 - dir2
    |
    - test2.py

After running the test1.py the directory structure look like this:

dir1
 |
 - test1.txt
 | 
 - test2.txt
 |
 - test1.py
 |
 - dir2
    |
    - test2.py

But after running the script I was expecting the directory structure to look like this:

dir1
 |
 - test1.txt
 |
 - test1.py
 |
 - dir2
    | 
    - test2.txt
    |
    - test2.py

I have tried searching ways to fix this but haven't found any.

So is there anyway to get something like I was expecting after running test1.py.

Upvotes: 1

Views: 602

Answers (1)

Chase
Chase

Reputation: 5615

Relative file paths like "test1.txt" are relative to the directory you run the script from. Since, you run test1.py from the same directory as itself - the relative path is resolved to the same directory as well. So test1.txt becomes /path/to/dir1/test1.txt

If you ran test1.py from within dir2, you'd see both text files in /path/to/dir2/.

This is how relative paths work in pretty much every language. If you want reliable path building, use os.path functions

cwd = os.path.dirname(os.path.abspath(__file__))

This will give you an absolute path to the file you use this on. So if you use this on test1.py - you get /path/to/dir1. Now you can use os.path.join to build your desired paths

Just for a complete example, to make test2.txt inside dir2 (which is inside dir1), assuming that cwd line is resolved in test1.py (i.e __file__ points to test1.py) you simply do

test2_path = os.path.join(cwd, 'dir2', 'test2.txt')
with open(test2_path, 'w') as f:
    ....

And, if cwd is resolved in test2.py (__file__ points to test2.py), you do

test2_path = os.path.join(cwd, 'test2.txt')

Upvotes: 2

Related Questions