gpt4 book ai didi

ruby - 读取文件时如何避免被 UTF-8 BOM 绊倒

转载 作者:数据小太阳 更新时间:2023-10-29 06:23:05 24 4
gpt4 key购买 nike

我正在使用最近添加了 Unicode BOM header (U+FEFF) 的数据提要,现在我的 rake 任务被它搞砸了。

我可以使用 file.gets[3..-1] 跳过前 3 个字节,但是是否有更优雅的方式来读取 Ruby 中的文件,它可以正确处理这个问题,无论 BOM 是有没有?

最佳答案

在 ruby​​ 1.9.2 中,您可以使用模式 r:bom|utf-8

text_without_bom = nil #define the variable outside the block to keep the data
File.open('file.txt', "r:bom|utf-8"){|file|
text_without_bom = file.read
}

text_without_bom = File.read('file.txt', encoding: 'bom|utf-8')

text_without_bom = File.read('file.txt', mode: 'r:bom|utf-8')

文件中是否提供 BOM 并不重要。


您还可以将编码选项与其他命令一起使用:

text_without_bom = File.readlines(@filename, "r:utf-8")

(你得到一个包含所有行的数组)。

或使用 CSV:

require 'csv'
CSV.open(@filename, 'r:bom|utf-8'){|csv|
csv.each{ |row| p row }
}

关于ruby - 读取文件时如何避免被 UTF-8 BOM 绊倒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/543225/

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