Import files not in the current working directory
<p>Let's say the program asks the user for a file name to read and then a file to write the processed data into. </p>

<p>Is there a way to get the directory of the needed file so the program can alter the current directory to use it? Or is there another way to access that file?</p>

<p>Welp, this is my first answer on SO, so hopefully I don't misunderstand the question and get off to a bad start. Here goes nothing...</p>

<p>Quite frankly, there isn't too much more to be said than what prior comments and answers have provided. While there are <a href="http://stackoverflow.com/questions/10174211/make-an-always-relative-to-current-module-file-path">"portable" ways to "ask" for a path relative to your current working directory</a>, such a design choice isn't quite as explicit, particularly with respect to what the user might think is happening. If this were all behind-the-scenes file manipulation, that's one thing, but in this case, <b>I, like the others, recommend you ask for the entire path to both the read and write files.</b> For the sake of completeness, you could start with this:</p>

<pre><code># responses should be of the form 
# full/path/from/home/directory/to/file/my_read_and_write_files.txt
fileToReadPath = input("Provide the full path to your read file: ")
fileToWritePath = input("Provide the full path to your write file: ")

with open(fileToReadPath, 'r') as readFile, open(fileToWritePath, 'w') as writeFile:
    # do stuff with your files here!
    # e.g. copy line by line from readFile to writeFile
    for line in readFile:
        writeFile.write(line)
</code></pre>

<p>Notice that the context manager (<code>with</code>) will automatically close the files for you when you're done. For simple stuff like this, I think the link above, <a href="https://docs.python.org/3/library/os.html#files-and-directories" rel="nofollow">this section on the os module</a> and <a href="https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">this section on the IO itself</a> of the python docs do a pretty good job of explaining your options and the toy example. </p>

python directory cwd