相关疑难解决方法(0)

如何在Python中逐行读取大文本文件,而不将其加载到内存中?

我需要逐行读取一个大文件.假设文件超过5GB,我需要读取每一行,但显然我不想使用,readlines()因为它会在内存中创建一个非常大的列表.

以下代码如何适用于此案例?xreadlines本身是一个一个地读入记忆吗?是否需要生成器表达式?

f = (line for line in open("log.txt").xreadlines())  # how much is loaded in memory?

f.next()  
Run Code Online (Sandbox Code Playgroud)

另外,我可以做什么来以相反的顺序读取它,就像Linux tail命令一样?

我发现:

http://code.google.com/p/pytailer/

" python头,尾和向后读取文本文件的行 "

两者都运作得很好!

python

218
推荐指数
8
解决办法
22万
查看次数

为什么python对文件句柄的数量有限制?

我编写了简单的测试代码,可以在python脚本中打开多少文件:

for i in xrange(2000):
    fp = open('files/file_%d' % i, 'w')
    fp.write(str(i))
    fp.close()

fps = []
for x in xrange(2000):
    h = open('files/file_%d' % x, 'r')
    print h.read()
    fps.append(h)
Run Code Online (Sandbox Code Playgroud)

我得到一个例外

IOError: [Errno 24] Too many open files: 'files/file_509'
Run Code Online (Sandbox Code Playgroud)

python

20
推荐指数
4
解决办法
2万
查看次数

fopen问题 - 打开的文件太多了

我有一个在Win XP上运行的多线程应用程序.在某个阶段,其中一个线程无法使用fopen函数打开现有文件._get_errno函数返回EMFILE,这意味着打开的文件太多.没有更多的文件描述符可用.我的平台的FOPEN_MAX是20._getmaxstdio返回512.我用WinDbg检查了这个,我看到大约有100个文件是打开的:

788 Handles
Type            Count
Event           201
Section         12
File            101
Port            3
Directory       3
Mutant          32
WindowStation   2
Semaphore       351
Key             12
Thread          63
Desktop         1
IoCompletion    6
KeyedEvent      1
Run Code Online (Sandbox Code Playgroud)

fopen失败的原因是什么?


编辑:

我写了简单的单线程测试应用程序.这个程序可以打开510文件.我不明白为什么这个应用程序可以打开更多文件,然后多线程应用程序.可能是因为文件句柄泄漏了吗?

#include <cstdio> 
#include <cassert> 
#include <cerrno> 
void main() 
{ 
    int counter(0); 

    while (true) 
    { 
        char buffer[256] = {0}; 
        sprintf(buffer, "C:\\temp\\abc\\abc%d.txt", counter++); 
        FILE* hFile = fopen(buffer, "wb+"); 
        if (0 == hFile) 
        { 
            // check error code 
            int err(0); 
            errno_t ret = _get_errno(&err); 
            assert(0 == …
Run Code Online (Sandbox Code Playgroud)

c++ windows fopen file-descriptor

4
推荐指数
1
解决办法
7854
查看次数

标签 统计

python ×2

c++ ×1

file-descriptor ×1

fopen ×1

windows ×1