1AntonyAwesome1
1AntonyAwesome1

Reputation: 11

How do i change the location directory of python open document?

i was just wondering how i can change the location/directory that python uses to navigate and open files.

I am a super noob so please use small words if you help me, and if you do, thanks.

In case it matter, i use two mass storage devices one is located under the A:\ and the other using the default C:. From memory i installed python under the A drive even though i know some parts are under the C drive. I also believe that i have set my mass storage devices up in AHCI or IDE.

Example Code:

File_Test = open("Test.txt", "r")

This then produces the error:

Traceback (most recent call last): File "", line 1, in File_Test = open("Test.txt", "r") IOError: [Errno 2] No such file or directory: 'Test.txt'"

Which from what i understand is python can't find the directory under which thise file is located.

I would really like to know how to make python locate files in my specified directory. If you can help i would be very appreciative, thanks.

Upvotes: 0

Views: 14069

Answers (2)

Sukrit Kalra
Sukrit Kalra

Reputation: 34543

Use the os.chdir() function.

>>> import os
>>> os.getcwd()
'/home/username'
>>> os.chdir(r'/home/username/Downloads')
>>> os.getcwd()
'/home/username/Downloads'

You can get the current working directory using the os.getcwd function. The os.chdir function changes the current working directory to some other directory that you specify. (one which contains your file) and then you can open the file using a normal open(fileName, 'r') call.

Upvotes: 3

chepner
chepner

Reputation: 532093

More precisely, the problem is that there is no file "Test.txt" in the directory Python considers its current working directory. You can see which directory that is by calling os.getcwd. There are two solutions.

First, you can change Python's working directory by calling os.chdir to be the directory where your file lives. (This is what Sukrit's answer alludes to.)

import os
# Assuming file is at C:\some\dir\Test.txt
os.chdir("C:\some\dir")
file_test = open("Test.txt", "r")

Second, you can simply pass the full, absolute path name to open:

file_test = open("C:\some\dir\Test.txt")

Upvotes: 0

Related Questions