-2

I am a beginner, working on python code in Visual Studio. I have created a dir Test_Folder with the following python file Test.py:

new_file = open('README.txt','w')
new_file.close()

The resulting file README.txt fro, Test.py is being created outside the Test_Folder:

my_dir
   ├── Test_Folder          
   │   ├── Test.py
   ├── README.txt          

Why does this happen? And how can I create the text file inside the same directory?

darthbhyrava
  • 505
  • 4
  • 14
Hack3r
  • 27
  • 1
  • 1
  • 6
  • 5
    Please share your code as pasted text, not as an image. – Mureinik Oct 29 '18 at 09:09
  • Are you running the .py file from inside Test_Folder (i.e. does your command prompt say you are in the same dir as the .py file)? – NotAnAmbiTurner Oct 29 '18 at 09:10
  • 1
    You are probably in an other working directory. Use this to figure which one: `print (os.getcwd())` and use this to change it `os.chdir()`. – Mathieu Oct 29 '18 at 09:10

1 Answers1

2

The file is created in the "current working directory" (cwd), which is the folder from where you ran the command python my_script.py.

If you run this:

cd /path/to/Test_folder
python Test.py

the file will be created in /path/to/Test_folder.

If you run

cd /path/to
python Test_folder/Test.py

the file will be created in /path/to.

If you want to see what is your concrete "current working directory" within your script:

>>> import os
>>> print(os.getcwd())
'/path/to/your_current_working_directory'

Since your run your script using VSCode, you can configure your "cwd" from the launch.json file in your project's folder. See this Q/A for more information:

{
    // [...]
    "cwd": "<Path to the directory>"
}
Antwane
  • 20,760
  • 7
  • 51
  • 84