简体   繁体   English

Ruby:将值写入CSV文件中的特定位置

[英]Ruby: Write a value to a specific location in CSV file

I'm still fairly new to coding and I'm trying to learn about manipulating CSV files. 我对编码还很陌生,并且正在尝试学习有关处理CSV文件的知识。

The code below opens a specified CSV file, goes to each url in the CSV file in column B (header = url), and finds the price on the webpage. 下面的代码打开一个指定的CSV文件,转到B列CSV文件中的每个网址(标题=网址),然后在网页上找到价格。

Example data from CSV file: CSV文件中的示例数据:

Store,URL,Price
Walmart,http://www.walmart.com/ip/HP-11.6-Stream-Laptop-PC-with-Intel-Celeron-Processor-2GB-Memory-32GB-Hard-Drive-Windows-8.1-and-Microsoft-Office-365-Personal-1-yr-subscription/39073484
Walmart,http://www.walmart.com/ip/Nextbook-10.1-Intel-Quad-Core-2-In-1-Detachable-Windows-8.1-Tablet/39092206
Walmart,http://www.walmart.com/ip/Nextbook-10.1-Intel-Quad-Core-2-In-1-Detachable-Windows-8.1-Tablet/39092206

I'm having trouble writing that price to the adjacent column C (header = price) in the same CSV. 我在将该价格写入同一CSV的相邻列C(标题=价格)时遇到了麻烦。

require 'nokogiri'
require 'open-uri'
require 'csv'

contents = CSV.open "mp_lookup.csv", headers: true, header_converters: :symbol
contents.each do |row|
  row_url = row[:url]
  goto_url = Nokogiri::HTML(open(row_url))
  new_price = goto_url.css('meta[itemprop="price"]')[0]['content']

#----
#In this section, I'm looking to write the value of new_price to the 3rd column in the same CSV file

#----

end

In the past, I've been able to use: 过去,我可以使用:

in_file = open("mp_lookup.csv", 'w')
in_file.write(new_price)

But this doesn't seem to work in this situation. 但这似乎在这种情况下不起作用。

Any help is appreciated! 任何帮助表示赞赏!

The simple answer is that you can refer to the :price column in the CSV file, just like you refer to the :url column. 简单的答案是,您可以引用CSV文件中的:price列,就像您引用:url列一样。 Try this code to set the price in the CSV object in memory: 尝试使用以下代码在内存中的CSV对象中设置价格:

row[:price] = new_price

After you've read through all of the records, you'll want to save the CSV file again. 阅读完所有记录后,您将需要再次保存CSV文件。 You can save it to any filename, but we'll simply overwrite the previous file in this example: 您可以将其保存为任何文件名,但是在此示例中,我们将简单地覆盖先前的文件:

CSV.open("mp_lookup.csv", "wb") do |csv|
  contents.each do |row|
      csv << row
  end
end

In a real production environment, you'd want to be more fault tolerant than this, and preserve the original file until the end of the process. 在实际的生产环境中,您希望比此更高的容错能力,并保留原始文件,直到过程结束。 However, this shows how to update the values in the price column for each row, and then save the changes to a file. 但是,这显示了如何更新每一行的价格列中的值,然后将更改保存到文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM