Reputation: 537
I would like to change the folder where a file is created in my Python Script.
Just now I have the next line:
file = open("scraping.txt", "w")
but the problem is that scraping.txt is saved in the root folder and I would like to save it in the same folder where the script is.
How can I do that?
Thanks
Upvotes: 0
Views: 857
Reputation: 4318
By default, python creates scraping.txt
in the directory from where you invoke the script. In your case, you are invoking the script from root directory thats why file is created at root directory.
you can use os.path.abspath(__file__)
for getting folder of your script.
import os
open(os.path.join(os.path.abspath(__file__),'..','scraping.txt'),'w')
Upvotes: 1
Reputation: 206
By default python creates file in you present working directory. You can know your present working directory using:
import os
os.getcwd()
Just change your directory to the desired one using:
os.chdir('new/directory')
Now create file under your desired path.
Upvotes: 0
Reputation: 6767
Either add the path to the file:
file = open('/path/to/scraping.txt', 'w')
Or use the os
module to change the directory:
import os
os.chdir('/path/to/')
file = open('scraping.txt', 'w')
Upvotes: 1
Reputation: 21873
you just need to add the path :
file = open("/PATH/TO/YOUR/FOLDER/scraping.txt", "w")
Upvotes: 0