簡體   English   中英

如何使用tcl逐行讀取大文件?

[英]how to read a large file line by line using tcl?

我使用while循環編寫了一段代碼,但是一行一行地讀取文件會花費太多時間。 有人可以幫我嗎? 我的代碼:

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

代碼看起來不錯。 它非常快(如果您使用的是Tcl的足夠新的版本;從歷史上看,有些Tcl的次要版本存在緩沖區管理問題),這就是您一次讀取一行的方式。

如果您一次可以讀取大量內容,則速度會稍快一些,但是您需要有足夠的內存來保存文件。 在上下文中,幾百萬行的文件通常沒有問題; 現代計算機可以很好地處理這種事情:

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

如果確實是一個大文件,則應執行以下操作以一次僅讀取一行。 使用您的方法會將全部內容讀入ram。

https://www.tcl.tk/man/tcl8.5/tutorial/Tcl24.html

#
# Count the number of lines in a text file
#
set infile [open "myfile.txt" r]
set number 0

#
# gets with two arguments returns the length of the line,
# -1 if the end of the file is found
#
while { [gets $infile line] >= 0 } {
    incr number
}
close $infile

puts "Number of lines: $number"

#
# Also report it in an external file
#
set outfile [open "report.out" w]
puts $outfile "Number of lines: $number"
close $outfile

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM