从任意文件中抓取数组

时间:2015-05-19 23:03:01

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

为了清晰而编辑。

我知道我们有文件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()

1 个答案:

答案 0 :(得分:0)

我对你的问题感到有些困惑,所以也许我现在没有解决这个问题,但是你看过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
相关问题