【问题标题】:How to get all the folder name from internal storage and show it in the text-field?如何从内部存储中获取所有文件夹名称并将其显示在文本字段中?
【发布时间】:2018-07-21 10:45:32
【问题描述】:

我想要做的是从特定位置查看文本字段中的所有文件夹名称。例如,给定的数据路径是-

android/data/

在这里,在数据路径中,我们有一些文件夹,例如 com.facebook.katanacom.android.browsercom.android.calendar 等。现在我要做的是在文本字段中显示所有文件夹名称。有什么办法吗?

【问题讨论】:

    标签: android python python-3.x kivy kivy-language


    【解决方案1】:

    类似这样的:

    import os
    p = "android/data/com.something"
    file = os.path.basename(p)
    

    文件现在包含:'com.something' 然后将文件分配给您的文本字段变量。例如:

    在你的 python 代码中:

    self.my-text-field.text = file
    

    在你的 kv 文件中:

    my-text-field:my-text-field
    TextInput:
        id: my-text-field
    

    【讨论】:

    • 假设有更多类似 com.example 的文件夹(例如 com.skype ),我想查看它们,程序是什么?
    • 在 Jones1220 的回答下查看我上面的评论:你会这样做:npath = os.path.split('/')。然后: n = len(npath) 这将为您提供路径元素的数量。随后:npath[0]、npath[1]、npath[2] 直到 npath[n] 将为您提供各个路径元素。
    • 在这里,在数据路径中,我们有一些文件夹,如 com.facebook.katanacom.facebook.browsercom.facebook.calendar 等。现在我要做的是在文本字段中显示所有文件夹名称.
    【解决方案2】:

    您可以使用 python 中的 os.path 模块:

    import os
    
    path = 'android/data/com.something'
    
    os.path.split(path)[-1]
    

    返回路径结构的最后一个元素:

    'com.something'
    

    编辑: 如果您需要数据路径的多个部分,请将其拆分为 /

    这将返回所有路径元素的列表。如果要查找具有共享模式的多个元素,可以使用 Regex 来查找这些元素。在您的示例中:

    import re
    
    path = 'android/data/com.something/com.facebook/com.skype'
    
    split_path = path.split('/')
    
    elements = [element for element in split_path if re.match(\A['com.'], element)]
    

    输出:

    ['com.something', 'com.facebook', 'com.skype']
    

    这里的re.match 包含以com. 开头的每个元素。当然你可以根据需要修改你的正则表达式。

    【讨论】:

    • 数据路径中是否有多个文件夹名需要查看?
    • 你会这样做:npath = os.path.split('/')。然后: n = len(npath) 这将为您提供路径元素的数量。随后:npath[0]、npath[1]、npath[2] 直到 npath[n] 将为您提供各个路径元素。
    • 我还不确定获取文件夹名称。
    • 你能举一个更具体的例子来说明你想要做什么吗?
    • 在这里,在数据路径中,我们有一些文件夹,如com.facebook.katanacom.facebook.browsercom.facebook.calendar 等。现在我要做的是在文本字段中显示所有文件夹名称.
    【解决方案3】:

    尝试这样做, 如果您使用的是相对路径,则需要使用第二行。否则跳过它 File file = new File(filename); file = new File(file.getAbsolutePath()); String directory = file.getParent(); File dirAsFile = file.getParentFile();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-31
      • 2021-02-12
      • 2023-03-11
      • 2021-03-03
      相关资源
      最近更新 更多