gpt4 book ai didi

ruby - 在 Ruby 中的 .each 循环中读取文件时移动到文件的最后一行

转载 作者:数据小太阳 更新时间:2023-10-29 07:56:52 25 4
gpt4 key购买 nike

我正在读取一个可以包含任意行数的文件。

我只需要保存前 1000 个左右,作为变量“recordsToParse”传入。

如果我达到了我的 1000 行限制,或者它设置的任何值,我需要将预告片信息保存在文件中以验证 total_records , total_amount等等

因此,我需要一种方法将我的“指针”从我在文件中的任何位置移动到最后一行,然后再运行一次。

file = File.open(file_name)

parsed_file_rows = Array.new
successful_records, failed_records = 0, 0
file_contract = file_contract['File_Contract']
output_file_name = file_name.gsub(/.TXT|.txt|.dat|.DAT/,'')

file.each do |line|
line.chomp!
line_contract = determine_row_type(file_contract, line)

if line_contract
parsed_row = parse_row_by_contract(line_contract, line)
parsed_file_rows << parsed_row
successful_records += 1
else
failed_records += 1
end

if (not recordsToParse.nil?)
if successful_records > recordsToParse
# move "pointer" to last line and go through loop once more
#break;
end
end

end
store_parsed_file('Parsed_File',"#{output_file_name}_parsed", parsed_file_rows)
[successful_records, failed_records]

最佳答案

使用 IO.seekIO::SEEK_END 将指针移动到文件末尾,然后向上移动到最后一个 CR,然后你有最后一个线。

这只有在文件很大时才值得,否则只需按照 file.each do |line| 到最后一行,或者你可以像这样阅读最后一行 IO .readlines("file.txt")[-1].

最简单的解决方案是使用像 elif 这样的 gem

require "elif"

lastline = Elif.open("bigfile.txt") { |f| f.gets }

毫无疑问,它会使用 seek 快速读取您的最后一行。

关于ruby - 在 Ruby 中的 .each 循环中读取文件时移动到文件的最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12010986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com