一个文本文件,我有一个文件名为ama.txt和文件的内容是这样的:如何修改红宝石
name age hobby sex
amit 45 music male
sumit 35 cricket female
现在我可以打开该文件是这样的:
File.open("ama.txt").each do
end
如何修改文件的hobby
列?
一个文本文件,我有一个文件名为ama.txt和文件的内容是这样的:如何修改红宝石
name age hobby sex
amit 45 music male
sumit 35 cricket female
现在我可以打开该文件是这样的:
File.open("ama.txt").each do
end
如何修改文件的hobby
列?
File.readlines("ama.txt").each do |line|
row = line.strip.split('\t') # use your delimiter symbol
row[2] = ... # hobby column
end
或者只是使用fastercsv宝石。
这样的事情一般模式大致如下:
cols = line.split(/\s+/)
之类的东西,然后您想编辑cols[2]
,但我不知道这些更改是否适合模式或什么。Ruby和大多数脚本语言一样,有很多内置的方法可以使这些步骤中的某些步骤更快,但这是基本模式。德米特里可能是正确的,一个CSV阅读器可以帮助你,但我看不出你的数据格式(或没有),所以我甚至都不会去了解这一点。
最后,不要粗鲁,但似乎你并不熟悉Ruby。为什么Ruby是一个需求?你知道另一种脚本语言吗?你对Ruby有多了解?一般来说,这里的人会帮助你处理事情,但不能简单地为你写代码。
要回答Amit关于步骤4的问题:如果您有一个新文件可以写入,您将拥有一个文件句柄 - 程序中指向打开文件的变量。您可以使用文件句柄作为puts
的接收器来写入该文件。这看起来很奇怪,因为puts
看起来像一个正常的功能,但它是a method call in Ruby。在irb
试试这个或短Ruby脚本:
fh = File.open('test.txt', 'w')
fh.puts "hello, world"
fh.close
另一个简单的例子:
#!/usr/bin/env ruby
out_file = File.open('output.txt', 'w')
File.open('input.txt', 'r').each do |line|
out_file.print line.sub('foo', 'bar')
end
out_file.close
# no need to close the input file since the block version closes it for us
# automagically
# Maybe better to put the whole thing in a double block, though you may
# find this harder to follow at first
File.open('output.txt', 'w') do |out_file|
File.open('input.txt', 'r').each do |line|
out_file.print line.sub('foo', 'bar')
end
end
,但它不工作文件ama.txt保持相同。什么做 – Milan 2010-07-20 13:00:10
梅德我必须把这个代码file.open(“ama.txt).each do end ?? – Milan 2010-07-20 13:01:30
电话不工作我想修改爱好列的值如何做到这一点?? – Milan 2010-07-20 13:15:45