Alex
Alex

Reputation: 537

How can I change the folder where a file is created in python?

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

Answers (4)

venpa
venpa

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

Nitin Verma
Nitin Verma

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

Ben
Ben

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

jrjc
jrjc

Reputation: 21873

you just need to add the path :

file = open("/PATH/TO/YOUR/FOLDER/scraping.txt", "w")

Upvotes: 0

Related Questions