【发布时间】:2019-07-08 19:57:29
【问题描述】:
我有适用于一个指定文件的代码。如何为多个文件迭代同一个函数?
下面的代码适用于 test3.txt 文件。我在一个文件夹中有多个文件(test1.txt、test2.txt、test3.txt ...)你能帮我遍历每个文件吗?我相信我必须更改第 6-7 行。请帮忙。我是 python 新手...
import os,csv,datefinder,re
import numpy as np
os.chdir('C:\Users\dul\Dropbox\Article')
with open("test3.txt", 'r') as file1:
text1=file1.read()
#locate the date of the article
matches = list(datefinder.find_dates(text1))
if len(matches) > 0:
date=matches[1]
strdate = str(date)
else:
print 'No dates found'
#locate the name of the company
matchcomp = re.search(r'Keywords:([^,]*)(,|$)', text1).group(1).strip()
#count the number of words in the article
matchcount = re.search(r'(.*) words', text1).group(1).strip()
#determine the article
def matchwho():
if 'This story was generated by' in text1:
return('1')
elif 'This story includes elements generated' in text1:
return('2')
elif 'Elements of this story were generated' in text1:
return('2')
elif 'Portions of this story were generated' in text1:
return('2')
else:
return('3')
matchw =str(matchwho())
#list the returns in a line
combid = matchcomp + "," + strdate + "," + matchw + "," + matchcount
#save in txt format
with open('outfile.txt', 'w') as outfile:
outfile.write(combid)
我希望返回附加在 outfile.txt 中
【问题讨论】:
-
您可以使用
os.walk()(或者更可能在此处使用os.dir())返回文件夹中的所有文件名。然后将您拥有的所有代码捆绑到def match_from_file(file)之类的函数中,并将文件名传递给该函数 -
@Reedinationer 是否会 os.dir() 对文件夹中的所有文本文件重复该功能?我试过了,但它只是没有用....
-
抱歉,我输入了错误的命令(
dir用于命令提示符)。您可以尝试files = os.listdir(),然后如果您想处理所有文件,您可以执行for file in files: print(file)或者您可能想添加if ".txt" in file:,这样您就只能获取该文件夹中的文本文件。os.walk()将让您递归地收集文件夹中的所有文件,因此如果您的所有文件都隐藏在一系列文件夹中,您可以使用它来代替 -
@Reedinationer 问题是,尽管使用了 os.listdir(),但我的第 6-7 行已经在其中指定了“test3.txt”。这不会禁止 os.listdir() 读取文件夹中的所有文本文件吗?
标签: python python-2.7