我有一个名为ama.txt的文件,文件内容如下:
name age hobby sex
amit 45 music male
sumit 35 cricket female
Run Code Online (Sandbox Code Playgroud)
现在我可以像这样打开文件:
File.open("ama.txt").each do
end
Run Code Online (Sandbox Code Playgroud)
如何修改hobby文件列?
Tel*_*hus 16
这种情况的一般模式大致如下:
cols = line.split(/\s+/),然后你想要编辑cols[2],虽然我不知道这些变化是适合模式还是什么.与大多数脚本语言一样,Ruby有许多内置方法可以使这些步骤更快,但这是基本模式.Dmitry可能是正确的,CSV阅读器会在这里帮助你,但我看不出你的数据格式是否合格(或不是),所以我甚至不打算进入.
最后,不要太粗鲁,但似乎你并不熟悉Ruby.为什么Ruby是一个要求?你知道另一种脚本语言吗?你对Ruby有多了解?一般来说,这里的人会帮助你解决问题,但不是简单地为你编写代码.
回答Amit关于第4步的问题:如果你有一个新的文件打开写,你将有一个文件句柄 - 程序中一个指向打开文件的变量.您可以使用filehandle作为接收器来写入该文件puts.这看起来很奇怪,因为它puts看起来像一个函数,但它是 Ruby中的方法调用.试试这个irb或简短的Ruby脚本:
fh = File.open('test.txt', 'w')
fh.puts "hello, world"
fh.close
Run Code Online (Sandbox Code Playgroud)
另一个简短例子:
#!/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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10846 次 |
| 最近记录: |