红宝石 2.6.3。
我一直在尝试将StringIO对象解析为CSV具有bom|utf-8编码的实例,以便去除 BOM 字符(不需要的)并将内容编码为 UTF-8:
require 'csv'
CSV_READ_OPTIONS = { headers: true, encoding: 'bom|utf-8' }.freeze
content = StringIO.new("\xEF\xBB\xBFid\n123")
first_row = CSV.parse(content, CSV_READ_OPTIONS).first
first_row.headers.first.include?("\xEF\xBB\xBF") # This returns true
Run Code Online (Sandbox Code Playgroud)
显然bom|utf-8编码不适用于StringIO对象,但我发现它适用于文件,例如:
require 'csv'
CSV_READ_OPTIONS = { headers: true, encoding: 'bom|utf-8' }.freeze
# File content is: "\xEF\xBB\xBFid\n12"
first_row = CSV.read('bom_content.csv', CSV_READ_OPTIONS).first
first_row.headers.first.include?("\xEF\xBB\xBF") # This returns false
Run Code Online (Sandbox Code Playgroud)
考虑到我需要StringIO直接使用,为什么CSV忽略bom|utf-8编码?有没有办法从StringIO实例中删除 BOM 字符?
谢谢!
我的应用程序允许用户上传最大50MB的csv文件.我想向用户显示上传文件的预览.我只能阅读csv的前5行吗?我目前正在使用CSV.read函数,显然这将读取整个文件并且速度很慢.
我有一个带有名称和 ID 的用户模型。
我想将用户中的所有列存储到一个 csv 文件中。
我如何使用 CSV.generate 函数来做到这一点?