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

Question:

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.

Asked By: 1AntonyAwesome1

||

Answers:

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.

Answered By: Sukrit Kalra

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:somedirTest.txt
os.chdir("C:somedir")
file_test = open("Test.txt", "r")

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

file_test = open("C:somedirTest.txt")
Answered By: chepner
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.