【问题标题】:Grabbing arrays from arbitrary files从任意文件中抓取数组
【发布时间】:2015-05-19 23:03:01
【问题描述】:

为清晰起见进行了编辑。

我知道我们有文件 IO 来访问文件元素并对其进行操作等。我的问题是我很好奇。

假设我们有几个不同的文件,在每个文件中我们可以假设只有一个list 包含此list 中的一些数据。

import os
def make_bars(self):
    for files in os.listdir(os.path.dirname(os.path.abspath(__file__))):
        if files.endswith('.txt'): # or some other file like .py
            a_list = open(files, "r").read()

【问题讨论】:

    标签: python arrays file python-3.x file-io


    【解决方案1】:

    我对你的问题有点困惑,所以也许我没有解决手头的问题,但你看过os.walk吗?

    for root, dirs, files in os.walk(SOME_ROOT_DIR):
        # root is SOME_ROOT_DIR, then each dir in dirs in turn
        # dirs is a list of all the directories in root
        # files is a list of all files in root
        for filepath in filter(lambda s: s.endswith(".py"), files):
            with open(filepath) as f:
                # do something with the .py file
    

    例如这样的目录列表:

    C:\USERS\ADSMITH\TMP\ROOT
    │   foobar.txt
    │   main.py
    │   tasks.py
    │
    └───subroot
            foo.py
            foobar.txt
    

    我能做到:

    import os
    
    for root, dirs, files in os.walk("C:/users/adsmith/tmp/root"):
        print("root is " + root)
        for filepath in files:
            if filepath.endswith('.txt') or filepath.startswith('tasks'):
                print(filepath)
    
    # OUTPUT:  NOTE THE RELATIVE PATHS
    root is C:/users/adsmith/tmp/root
    foobar.txt
    tasks.py
    root is C:/users/adsmith/tmp/root\subroot
    foobar.txt
    

    【讨论】:

    • 我看过os.walk 并考虑使用它,但如果我没记错的话 os.walk 不会获取绝对路径,所以我选择了替代方法。我的问题更倾向于如果我们将所有内容都放在.py 文件中,这是否可能,我意识到这现在相当混乱。我相当肯定您的解决方案,我的解决方案适用于目录中的 .txt 文件和其他文件类型,因为我没有运行任何一个块。但是,如果我们在一些.py 文件中定义了一些数组,是否可以过滤掉数组的变量名并获取数据?
    • @Skeletor 因为你有根和相对路径,所以绝对路径总是os.path.join(root, filepath)
    猜你喜欢
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2011-02-03
    • 1970-01-01
    • 2011-12-14
    相关资源
    最近更新 更多