新手求助,python字符串查找的问题,谢谢!
要求在同一个文件夹下的多个TXT文档中查找用户输入的关键字,统计个数,并写入到一个文件中。本人使用的版本为PYTHON 2.4.1。共288个文件,每个文件应当含有47条记录,之前的文件都正确,可最后一个文件中的记录只能显示到40条左右,通过DEBUG之后,发现程序每次运行到最后一个文件的最后几行时,就自动结束了。而如果只读一个TXT文档的话,可以将其写入到ALL文件中,但是程序什么都不做,直接输出为0。实在是搞不明白,请各位高人帮忙指导一下,感激不尽!
程序代码:
# File: readline-example-1.py
import os,glob
f3 = open(r'c:\python\all.txt','w')
path = 'd:\AWS_JGJ_20120703'
os.chdir(path)
for fname in glob.glob('*.TXT'):
f1 = open(fname,'r')
text = f1.read()
f3.write(text)
f2 = open(r'c:\python\result.txt','w')
f4=open(r'c:\python\all.txt','r')
line = f4.readline
linen = 1
num = raw_input('please enter a number(like B0004):'
n=0
while line:
if not line.find(num) ==-1:
n=n+1
print n
print line
f2.write(line+'\n')
linen +=1
line = f4.readline()
print line
print n/1.0
print n/288.0
f1.close()
f2.close()
f3.close()
f4.close()
[解决办法]
# File: readline-example-1.pyimport os, glob, fileinputimport itertoolsstream = fileinput.FileInput(glob.glob(os.path.join( r'd:\AWS_JGJ_20120703', '*.TXT')))num = raw_input('please enter a number(like B0004):')n=0with open(r'c:\python\result.txt','w') as f2: for line in itertools.ifilter(lambda ln: num in ln, stream()): n += 1 f2.write(line)print n/1.0print n/288.0
[解决办法]
import os,globf3 = open(r'c:\python\all.txt','w')path = 'd:\AWS_JGJ_20120703'os.chdir(path)for fname in glob.glob('*.TXT'): f1 = open(fname,'r') text = f1.read() f3.write(text)f3.close()