帮忙改改python的小程序
现在有个txt文档,把第一列的不同的数放进各自的txt文件里,比如说第一个数是a就放进a.txt里,b就放进b.txt里。我写了个程序,对小文件可以用,但是对大文件好像不行,老是报错IOError: [Errno 24] Too many open files。 请各位老师帮忙看看修改下我的程序
import os, sys
infile = open ('1.txt')
outfiledict = {}
for row in infile:
row = row.strip()
parts = row.split(';')
if parts[0] not in outfiledict:
outfiledict[parts[0]] = open('/home/user/python/a/%s.txt' % parts[0], 'w')
outfile = outfiledict[parts[0]]
outfile.write(row + '\n')
infile.close()
for outfile in outfiledict.values():
outfile.close()
#!/usr/bin/python
# encoding: utf-8
from itertools import imap
class BufferedText:
def __init__(self, fname):
self.fname = fname
self.buff = []
def close(self):
self.flush()
def append(self, ln):
self.buff.append(ln)
if self.buff > self.MAXSIZE:
self.flush()
def flush(self):
with open(self.fname), 'at') as handle:
handle.writelines(self.buff)
self.buff = []
def p(ln):
ln = ln.strip()
return ln.strip(';')[0], ln
for part, ln in imap(p, open('1.txt')):
outfiledict.setdefault(part,
BufferedText('/home/user/python/a/%s.txt' % part)
).append(ln)
for handle in outfiledict.values():
handle.close()
# -*- coding:utf-8 -*-
ssFile = file('1.txt', 'r') #读文件
while True:
rl = ssFile.readline()
if len(rl) == 0:
break
rl = str(rl).replace('\n', '')
cnts = str(rl).split(";")
name = cnts[0]# 新文件名
cl = cnts[1:]
cnt = reduce(lambda x, y: int(x) + int(y), cl)# 求列表和
#print cl,cnt
nFile = file(name, 'a')# 打开文件并且指针移到文件末,如果文件不存在则创建
nFile.writelines(rl + ' = (' + str(cnt) + ')' + '\n')
nFile.close()
#print rl, name
ssFile.close()
ulimit -HSn 20000
import os, sys
infile = open ('1.txt')
outfiledict = {}
for row in infile:
row = row.strip()
parts = row.split(';')
if parts[0] not in outfiledict:
outfiledict[parts[0]] = open('/home/user/python/a/%s.txt' % parts[0], 'w')
outfile = outfiledict[parts[0]]
outfile.write(row + '\n')
outfile.close()
infile.close()
#for outfile in outfiledict.values():
# outfile.close()