【问题标题】:how to list names of all files from selected directory and subdirectories with in directory using tkinter如何使用tkinter在目录中列出所选目录和子目录中所有文件的名称
【发布时间】:2017-07-14 04:40:14
【问题描述】:

如何使用 tkinter 在目录中列出所选目录和子目录中所有文件的名称。这是我的代码。

def openDirectory(self):
        self.dirname = tkFileDialog.askdirectory(parent=self.root, 
        initialdir='/home/', title='Select your database' )
        self.files=os.listdir(self.dirname)
        print self.files

它只是列出目录中的文件。如果目录包含子目录,则会给出错误消息。我想列出目录的所有文件和子目录文件名。

【问题讨论】:

    标签: python-2.7 tkinter opendir


    【解决方案1】:

    两件事:

    1. os.listdir 应该为您提供指定路径中所有项目的名称。这包括文件和目录:https://docs.python.org/2/library/os.html#os.listdir。如果你想从os.listdir获取完整路径,你可以试试

    self.files = [os.path.join(self.dirname, item) for item in os.listdir(self.dirname)]

    1. 另一个选项是使用模块glob。如果你给glob.glob 一个完整的路径,它也应该给你一个所有项目的列表。例如:

      from glob import glob ... self.files = glob(os.path.join(self.dirname, '*'))

    【讨论】:

    • 请编辑我的代码..我的要求只是打印目录和子目录中存在的所有文件名@AetherUnbound
    • 您想要完整路径还是只想要名称?
    • def openDirectory(self): self.dirname = tkFileDialog.askdirectory(parent=self.root, initialdir='/home/', title='选择你的数据库') path=self.dirname for root, dirs, self.files in os.walk(path): for file in self.files: if file.endswith('.txt') | file.endswith('.pdf') | file.endswith('.pptx') | file.endswith('.docx') | file.endswith('.csv') | file.endswith('.xlsx'): #files=os.listdir(self.dirname) print (os.path.join(root, file))
    • 我使用上面的代码来访问所有文件名并成功..现在我想将所有这些文件存储在一个数组中..我该怎么做? @AetherUnbound
    • 你想要文件的完整路径还是文件名?
    猜你喜欢
    • 2012-11-14
    • 2012-09-02
    • 2016-01-16
    • 2011-03-01
    • 2014-03-08
    • 1970-01-01
    • 2014-10-16
    相关资源
    最近更新 更多