Python/Spyder: General Working Directory
<p>So far I have code that opens a text file, manipulates it into a pandas data file, then exports to excel.</p>

<p>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.</p>

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

<hr>

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

<pre><code>with open(r'file.txt', 'r') as data_file:
</code></pre>

<p>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.</p>

<p>The answer that you are technically looking for is using <code>os.chdir()</code> as follows</p>

<pre><code>import os
os.chdir('.', 'data')
#THE REST OF THE CODE IS THE SAME
with open(r'file.txt', 'r') as data_file:
</code></pre>

<p>A safer answer would however be </p>

<pre><code>def doTheThing(fName):
    return os.path.join(os.getcwd(),'data',fName)

with open(doTheThing('file.txt'), 'r') as data_file:
</code></pre>

python python-3.x directory spyder