如何使用python运行多个文件

时间:2013-03-23 16:57:40

标签: python python-2.7

我正在尝试从桌面上的文件夹中运行多个文本文件,我必须从中搜索单词olympic,如果它在50个文本文件中找到olympic,那么应该将它保存在output.txt中,就像 textfile1 = 2 textfile2 = 1,依此类推至texfile = 50

import glob
import re
write_file = open("output.txt")
flist = glob.glob("./*.py")   # adjust glob pattern as desired
print flist
print " lines : path to file"
for fpath in flist:
    with open(fpath) as f: #open files
        lines = f.readlines()
        if (lines == 'olympic'):
            write_file.write("%s" % lines) #write the results
        print "%6d : %s" % (len(lines),fpath)
        #with open securely opens and closes the file
write_file.close() # close file

这就是我想要做的,但是我知道它充满了错误:)

我正在尝试运行多个文件,但不是手动运行,我希望它能自动运行整个目录/文件夹的文件并将其输出保存在一个文本文件中。“I have 50 text files and all files have word olympic , some have 1 some have 2/3 etc , i want to count the words from each text file and than save their output in one text file , like textfile1 = 2 , textfile2 = 3 etc in output.txt

2 个答案:

答案 0 :(得分:0)

试试这个

import os
import re

filelist = [file for file in os.listdir('.') if '.py' in file]

for file in filelist:
  f = open(file,"r")
    lines = f.readlines()
    sum=0
    sum1=0
    for line in lines:
      if "olympics" in line:
        len(re.findall('\Wolympics\W', line))
        sum=sum+1
        print sum
      elif "Olympics" in line:
        sum1=sum1+1
        print sum1
    print "%6d : %s" % (len(line),file.name)
    f.close()

不确定你要做什么,但我试了一下......

答案 1 :(得分:0)

类似的东西:

<强> fetch.py​​

#! /usr/bin/env python
import os
import sys


def get_counts(filepath, niddle):
    with open(filepath, 'rb') as f:
        return f.read().count(niddle)


if __name__ == '__main__':
    folder = sys.argv[1]
    niddle = sys.argv[2]
    assert os.path.isdir(folder), "Not a folder"
    output = open('results.txt', 'w')
    for dirpath, dirnames, filenames in os.walk(folder):
        for filename in filenames:
            if not filename.endswith('.html'): # or whatever
                continue
            filepath = os.path.abspath('%s/%s' % (dirpath, filename))
            result = '%s = %d' % (filepath, get_counts(filepath, niddle))
            output.write(result)
    output.close()

用作:

$ python fetch.py /path/to/search olimpic