导入不在当前工作目录中的文件

时间:2016-08-30 02:57:24

标签: python directory cwd

假设程序要求用户读取文件名,然后写入要将处理过的数据写入的文件。

有没有办法获取所需文件的目录,以便程序可以更改当前目录以使用它?或者是否有其他方式来访问该文件?

3 个答案:

答案 0 :(得分:0)

如果用户输入了包含目录的完整文件路径,则可以解析它(使用sys.path),然后解析os.chdir()。

答案 1 :(得分:0)

通过使用Tkinter使用文件上传框提示它们而不是让他们输入文件,您可以让用户更容易。当他们选择文件时,它会为您提供完整的文件路径。

from tkinter import filedialog

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

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

不是说要求用户输入完整的文件路径会导致问题,但从个人经验来看,并不是每个人都能为您提供您想要的输入(更不用说并非每个人都知道文件路径语法)了,这个例子会减少误差范围。

答案 2 :(得分:0)

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.