Skip to main content
 首页 » 编程设计

python之如何失败并显示错误消息 "Too many open files in python"

2025年05月04日19yyy_WW

我创建了 10000 个文件——我的默认限制是“ulimit -n 1024”——我预计下面的脚本会失败并显示“打开的文件太多”之类的消息,但它并没有失败。 (/tmp/files 有 10000 个文件)

关于我哪里出错的任何想法?

import os 
listfiles=os.listdir('/tmp/files') 
count=0 
f='' 
for file in listfiles: 
        fn=f+str(count) 
        fn=open(file,'w') 
        fn.write('hello') 
        print 'file=',file 
        count=count+1 
 
print count 

请您参考如下方法:

for file in listfiles: 
        fn = f+str(count)    # what is this supposed to do? 
        fn = open(file,'w')  # old file handle gets garbage collected and closed 
        fn.write('hello') 
        print 'file=',file 
        count = count + 1 

每次重新绑定(bind) fn 之前的文件都会关闭。例如,在 jython 中,文件可能不会立即关闭,但很可能在超过 1024 个文件限制之前仍会收集并关闭垃圾

尝试将文件对象存储在这样的列表中:

import os 
listfiles = os.listdir('/tmp/files') 
count = 0 
f = '' 
fn = [] 
for file in listfiles: 
        fn.append(open(file,'w')) 
        fn[-1].write('hello') 
        print 'file=',file 
        count = count + 1 
 
print count