Vikas Rajasekaran
Vikas Rajasekaran

Reputation: 71

Import files not in the current working directory

Let's say the program asks the user for a file name to read and then a file to write the processed data into.

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?

Upvotes: 0

Views: 748

Answers (3)

StarFox
StarFox

Reputation: 637

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

Quite frankly, there isn't too much more to be said than what prior comments and answers have provided. While there are "portable" ways to "ask" for a path relative to your current working directory, 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, I, like the others, recommend you ask for the entire path to both the read and write files. For the sake of completeness, you could start with this:

# 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)

Notice that the context manager (with) will automatically close the files for you when you're done. For simple stuff like this, I think the link above, this section on the os module and this section on the IO itself of the python docs do a pretty good job of explaining your options and the toy example.

Upvotes: 0

Harrison
Harrison

Reputation: 5386

You could make it even easier for the user by using Tkinter to prompt them with a file upload box rather than asking them to type it in. When they select a file it will give you the full file path.

from tkinter import filedialog

# this gives you the full file path
filepath = askopenfilename()

print filepath
# or do whatever you want with the file path

Not saying that asking users to type in a full file path will cause issues, but from personal experience not everyone gives you the input that you'd like (not to mention not everyones knows file path syntax), and this example would reduce the error margin.

Upvotes: 0

ddbug
ddbug

Reputation: 1539

If the user enters the complete file path with the directory, you can parse it (using sys.path) and then os.chdir() there.

Upvotes: 0

Related Questions