[英]How to carry in a list the name each file from a directory with python?
I am applying some regex to a folder full of .txt files in order to extract some specific patterns like this: 我正在将一些正则表达式应用到一个充满.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_)
And the output is the desired content of all the files in a list: 输出是列表中所有文件的所需内容:
[interesting stuff 1]
[interesting stuff 2]
[interesting stuff 3]
...
[interesting stuff n]
[interesting stuff n-1]
How can I carry or bind to the list the name of each document file, ie something like this: 如何将每个文档文件的名称携带或绑定到列表,例如:
[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
Thanks in advance guys. 在此先感谢大家。
If you want to print the list and then the filename without a newline between the two, you will first have to turn the list into a string, then strip off the brackets from around the list. 如果要打印列表,然后再打印文件名,且两者之间没有换行符,则必须先将列表转换为字符串,然后再删除列表中的括号。 After that you can grab the filename from the filepath that you have, and put the two together. 之后,您可以从已有的文件路径中获取文件名,然后将两者放在一起。
See code below; 参见下面的代码;
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.