簡體   English   中英

python-如何使用python列出目錄中每個文件的名稱?

[英]How to carry in a list the name each file from a directory with python?

我正在將一些正則表達式應用到一個充滿.txt文件的文件夾中,以提取一些特定的模式,例如:

def retrive(directory, a_regex):
    for filename in glob.glob(os.path.join(directory, '*.txt')):
        with open(filename, 'r') as file:
            important_stuff = re.findall(a_regex, file.read(), re.S)
            my_list = [tuple([j.split()[0] for j in i]) for i in important_stuff]
            print my_list


lists_per_file = retrive(directory,regex_)

輸出是列表中所有文件的所需內容:

[interesting stuff 1]
[interesting stuff 2]
[interesting stuff 3]
...
[interesting stuff n]
[interesting stuff n-1]

如何將每個文檔文件的名稱攜帶或綁定到列表,例如:

[interesting stuff 1], name_of_document_1
[interesting stuff 2], name_of_document_2
[interesting stuff 3],name_of_document_3
...
[interesting stuff n], name_of_document_n
[interesting stuff n-1], name_of_document_n-1

在此先感謝大家。

如果要打印列表,然后再打印文件名,且兩者之間沒有換行符,則必須先將列表轉換為字符串,然后再刪除列表中的括號。 之后,您可以從已有的文件路徑中獲取文件名,然后將兩者放在一起。

參見下面的代碼;

def retrive(directory, a_regex):
    for filename in glob.glob(os.path.join(directory, '*.txt')):
        with open(filename, 'r') as file:
            important_stuff = re.findall(a_regex, file.read(), re.S)
            my_list = [tuple([j.split()[0] for j in i]) for i in important_stuff]
            # print my_list # old line
            print str(my_list).strip('[]') + filename.split('/')[-1]


lists_per_file = retrive(directory,regex_)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM