如何使用tcl逐行读取大文件? [英] how to read a large file line by line using tcl?

查看:1707
本文介绍了如何使用tcl逐行读取大文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用while循环编写了一段代码,但是一行一行地读取文件会花费太多时间.有人可以帮我吗? 我的代码:

I've written one piece of code by using a while loop but it will take too much time to read the file line by line. Can any one help me please? my code :

   set a [open myfile r]              
   while {[gets $a line]>=0} {   
     "do somethig by using the line variable" 
   }

推荐答案

代码看起来不错.速度非常快(如果您使用的是Tcl的足够新的版本;从历史上看,有些Tcl的次要版本存在缓冲区管理问题),这就是您一次读取一行的方式.

The code looks fine. It's pretty quick (if you're using a sufficiently new version of Tcl; historically, there were some minor versions of Tcl that had buffer management problems) and is how you read a line at a time.

如果您一次可以读取大量内容,则速度会稍快一些,但随后您需要有足够的内存来保存文件.在上下文中,几百万行的文件通常是没有问题的.现代计算机可以很好地处理这种事情:

It's a little faster if you can read in larger amounts at once, but then you need to have enough memory to hold the file. To put that in context, files that are a few million lines are usually no problem; modern computers can handle that sort of thing just fine:

set a [open myfile]
set lines [split [read $a] "\n"]
close $a;                          # Saves a few bytes :-)
foreach line $lines {
    # do something with each line...
}

这篇关于如何使用tcl逐行读取大文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆