【问题标题】:How do I access a file in a sub-directory on user input without having to state the directory in Python 2.7.11?如何访问用户输入的子目录中的文件,而无需在 Python 2.7.11 中声明目录?
【发布时间】:2016-08-17 15:51:25
【问题描述】:

我有一个程序,它依赖于用户输入来输入文件,以便程序在 Python 2.7.11 中打开。我在原始目录Detector 中名为TestCases 的子目录中拥有所有这些文件,但是从超级目录运行程序时,我似乎无法访问TestCases 中的文件。我尝试使用os.path.join,但无济于事。这是我的代码:

import os.path
def __init__(self):
    self.file = None
    os.path.join('Detector', 'TestCases')

    while self.file == None:
        self.input = raw_input('What file to open? ')
        try:
            self.file = open(self.input, 'r')
        except:
            print "Can't find file."

我运行程序时的终端如下:

>>> What file to open? test.txt # From the TestCases directory
>>> Can't find file.
>>> What file to open? ...

我是否错误地使用了os.path.join?我认为它应该链接两个目录,以便在从超级目录运行程序时可以从子目录访问文件。

【问题讨论】:

  • 您正试图在当前目录中打开文件,而不是在TestCases 目录中

标签: python python-2.7 file path directory


【解决方案1】:

您正在使用 os.path.join('Detector', 'TestCases'),它应该返回 'Detector/TestCases',但您没有将该变量存储在任何地方。

我假设您在 Detector 目录中,并且您想在 TestCases 中打开文件。在这种情况下,您可以使用路径连接(它连接其参数并返回结果):

    import os.path

    file = None
    while not file:
        input = raw_input('What file to open? ')
        try:
            filepath = os.path.join('TestCases', input)
            file = open(filepath, 'r')
        except IOError:
            print "Can't find " + input

我已经存储了 os.path.join 的结果,所以你可以看到它并没有改变目录,它只是连接它的参数,也许你认为这个函数会改变目录,你可以用 os .chdir.

先用简单的脚本或者终端试试,会省去很多麻烦。

【讨论】:

  • 如果出现此错误,您的脚本可能不在 Director 目录中,因此我建议您提供 TestCases 目录的完整路径,并将其与 Jose J 示例中的输入一起加入跨度>
【解决方案2】:

关于os.path.join的文档

智能地加入一个或多个路径组件。返回值是路径的串联...

您似乎希望它设置某种 PATH 变量或影响当前工作目录。首先,在您的代码中添加类似这样的内容就足够了:

open(os.path.join("TestCases",self.input), 'r')

【讨论】:

    猜你喜欢
    • 2021-03-11
    • 2015-07-24
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多