Destroxia Destroxia - 1 year ago 95
Python Question

Python/Spyder: General Working Directory

So far I have code that opens a text file, manipulates it into a pandas data file, then exports to excel.

I'm sharing this code with other people, and we all have the same working directory within Spyder. All the code works fine, the only lines I want to manipulate are the opening of the file, and the exporting of the file.

with open(r'C:\Users\"my_name"\Desktop\data\file.txt', 'r') as data_file:

The issue here is, I want to set my working directory to just "\data" so that I can just write:

with open(r'file.txt', 'r') as data_file:

this way, the people I send it to, who also have "\data" as their working directory on their computer can just run the code, and it will select the "file.txt" that is in their data directory.

Answer Source

The answer that you are technically looking for is using os.chdir() as follows

import os
os.chdir('.', 'data')
with open(r'file.txt', 'r') as data_file:

A safer answer would however be

def doTheThing(fName):
    return os.path.join(os.getcwd(),'data',fName)

with open(doTheThing('file.txt'), 'r') as data_file: