Reputation: 371
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.
Upvotes: 2
Views: 1387
Reputation: 4200
The answer that you are technically looking for is using os.chdir()
as follows
import os
os.chdir('.', 'data')
#THE REST OF THE CODE IS THE SAME
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:
Upvotes: 2