如何在多个部分中提取和拆分字符串

时间:2017-06-07 10:22:33

标签: python

我想基于某些可能包含不同文件格式的模式在目录中搜索和拆分不同的文件:

/path/


somefile.txt 2010-01-01
file.txt 2010-01-02
f.txt 2010-01-03
test.txt 2010-01-04
photo.jpg 2010-01-04
script.py  2010-01-05

为了得到:

somefile.txt 
file.txt 
f.txt 
test.txt 

首先,我想要捕获包含.txt的所有文件并相应地拆分它们:

def catch_txt(path):
    result = [os.path.join(path, f) for f in os.listdir(path) if 
re.search(r"\w+\.\w+\txt", f)]
    splitted_result = [files for files in result if 
re.split(r"\w+\.\w+\txt", f)]
    # some other stuff
    return splitted_result

但只提供一个emtpy列表。

3 个答案:

答案 0 :(得分:0)

您可以使用列表推导来获取.txt:

res = [ i.split(" ")[0] for i in os.listdir(path) if '.txt' in i ]

答案 1 :(得分:0)

你的模式:

r"\w+\.\w+\txt"

寻找:

  1. 单词字符,一次或多次,然后是......
  2. 一个字面点,然后是......
  3. 单词字符一次或多次,然后是......
  4. 制表符,后跟......
  5. 字面字符' xt'。
  6. 因此您的模式将匹配文件名,如:

     hello.a    xt
    

    如果您想匹配以下文件名:

    hello.txt
    

    然后您需要使用如下模式:

    r"\w+\.txt"
    

答案 2 :(得分:0)

这是一个不使用re的解决方案。假设您的文件类型列表很短,您只需为每个文件类型创建一个列表

import os 

files = [f for f in os.listdir('.') if os.path.isfile(f)]
txt_files = [] #create additional lists/loops for each filetype
for file in files:
        if file.endswith('.txt'):
            txt_files.append(file)
print (txt_files)