c# - 读取文件特定行号的有效方法。 (奖金 : Python Manual Misprint)

标签 c# .net python file

我有一个 100 GB 的文本文件,它是来自数据库的 BCP 转储。当我尝试使用 BULK INSERT 导入它时,我在第 219506324 行遇到了一个神秘错误。在解决这个问题之前,我希望看到这一行,但是我最喜欢的方法是

import linecache
print linecache.getline(filename, linenumber)

正在抛出一个MemoryError。有趣的是the manual says “这个函数永远不会抛出异常。” 在这个大文件上,它在我尝试读取第 1 行时抛出一个异常,并且我有大约 6GB 的可用 RAM...

我想知道到达那条无法到达的线路的最优雅方法是什么。可用的工具有 Python 2、Python 3 和 C# 4 (Visual Studio 2010)。是的,我知道我总是可以做类似的事情

var line = 0;
using (var stream = new StreamReader(File.OpenRead(@"s:\source\transactions.dat")))
{
     while (++line < 219506324) stream.ReadLine(); //waste some cycles
     Console.WriteLine(stream.ReadLine());
}

哪个可行,但我怀疑这是优雅的方式。

编辑: 我正在等待关闭此线程,因为包含该文件的硬盘现在正被另一个进程使用。我将测试建议的方法和报告时间。谢谢大家的建议和意见。

结果在 我实现了 Gabes 和 Alexes 方法以查看哪个更快。如果我做错了什么,请告诉我。我将使用 Gabe 建议的方法在我的 100GB 文件中获取第 1000 万行,然后使用 Alex 建议的方法,我将其粗略地翻译成 C#...我自己唯一添加的是首先阅读 300 MB 文件到内存只是为了清除硬盘缓存。

const string file = @"x:\....dat"; // 100 GB file
const string otherFile = @"x:\....dat"; // 300 MB file
const int linenumber = 10000000;

ClearHDDCache(otherFile);
GabeMethod(file, linenumber);  //Gabe's method

ClearHDDCache(otherFile);
AlexMethod(file, linenumber);  //Alex's method

// Results
// Gabe's method: 8290 (ms)
// Alex's method: 13455 (ms)

gabe的方法实现如下:

var gabe = new Stopwatch();
gabe.Start();
var data = File.ReadLines(file).ElementAt(linenumber - 1);
gabe.Stop();
Console.WriteLine("Gabe's method: {0} (ms)",  gabe.ElapsedMilliseconds);

虽然 Alex 的方法有点诡异:

var alex = new Stopwatch();
alex.Start();
const int buffersize = 100 * 1024; //bytes
var buffer = new byte[buffersize];
var counter = 0;
using (var filestream = File.OpenRead(file))
{
    while (true) // Cutting corners here...
    {
        filestream.Read(buffer, 0, buffersize);
        //At this point we could probably launch an async read into the next chunk...
        var linesread = buffer.Count(b => b == 10); //10 is ASCII linebreak.
        if (counter + linesread >= linenumber) break;
        counter += linesread;
    }
}
//The downside of this method is that we have to assume that the line fit into the buffer, or do something clever...er
var data = new ASCIIEncoding().GetString(buffer).Split('\n').ElementAt(linenumber - counter - 1);
alex.Stop();
Console.WriteLine("Alex's method: {0} (ms)", alex.ElapsedMilliseconds);

因此,除非 Alex 愿意发表评论,否则我会将 Gabe 的解决方案标记为已接受。

最佳答案

这是我在 C# 中的优雅版本:

Console.Write(File.ReadLines(@"s:\source\transactions.dat").ElementAt(219506323));

或更一般的:

Console.Write(File.ReadLines(filename).ElementAt(linenumber - 1));

当然,您可能希望在给定行前后显示一些上下文:

Console.Write(string.Join("\n",
              File.ReadLines(filename).Skip(linenumber - 5).Take(10)));

或更流利地说:

File
.ReadLines(filename)
.Skip(linenumber - 5)
.Take(10)
.AsObservable()
.Do(Console.WriteLine);

顺便说一句,linecache 模块对大文件没有任何巧妙处理。它只是将整个内容读入,并将其全部保存在内存中。它捕获的唯一异常是与 I/O 相关的(无法访问文件、找不到文件等)。这是代码的重要部分:

    fp = open(fullname, 'rU')
    lines = fp.readlines()
    fp.close()

换句话说,它试图将整个 100GB 的文件放入 6GB 的 RAM 中!手册应该说的可能是“此函数永远不会抛出异常如果它无法访问文件。”

关于c# - 读取文件特定行号的有效方法。 (奖金 : Python Manual Misprint),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3589327/

相关文章:

php - 我需要 mysql-client 来进行 PHP/Python 等交互吗?

Python - 将 HTML 文件中的内容输出到电子表格

c# - 我对 Parallel.ForEach 做错了什么

c# - 如何在where子句中将字符串转换为DateTime?

c# - VB.NET WithEvents 关键字行为 - VB.NET 编译器限制?

c# - 解析大双值C#

Python ftplib 和 storbinary

c# - IValueConverter 和异常验证

c# - ASP.NET Core - 从类库查看

.net - 验证sqlite数据库中的数据未被其他人修改(即对数据签名)