我有两个文本文件,master.txt和926.txt。如果926.txt中有一行不在master.txt中,我想写一个新文件notinbook.txt。
我写了我能想到的最好的东西,但鉴于我是一个可怕的/新手程序员,它失败了。这就是我所拥有的
g = File.new("notinbook.txt", "w")
File.open("926.txt", "r") do |f|
while (line = f.gets)
x = line.chomp
if
File.open("master.txt","w") do |h|
end
while (line = h.gets)
if line.chomp != x
puts line
end
end
end
end
end
g.close
当然,它失败了。谢谢!
答案 0 :(得分:12)
这应该有效:
f1 = IO.readlines("926.txt").map(&:chomp)
f2 = IO.readlines("master.txt").map(&:chomp)
File.open("notinbook.txt","w"){ |f| f.write((f1-f2).join("\n")) }
这是我的测试:
<强> 926.txt
line1
line2
line3
line4
line5
<强> master.txt
line1
line2
line4
<强> notinbook.txt
line3
line5
答案 1 :(得分:1)
您可以这样做:
master_lines = []
File.open("notinbook.txt","w") do |result|
File.open("master.txt","r") do |master|
master.each_line do |line|
master_lines << line.chomp
end
end
File.open("926.txt","r") do |query|
query.each_line do |line|
if !master_lines.include? line.chomp
result.puts line.chomp
end
end
end
end
答案 2 :(得分:0)
答案 3 :(得分:0)
希望这有帮助
dir = File.dirname(__FILE__)
notinbook = "#{dir}/notinbook.txt"
master = "#{dir}/master.txt"
f926 = "#{dir}/926.txt"
def file_into_ary(file)
ary = []
File.open(file).each{ |line| ary << line }
return ary
end
def write_difference(file, diff)
File.open(file, 'w') do |file|
diff.each do |line|
file.write(line)
end
end
end
diff = file_into_ary(f926) - file_into_ary(master)
write_difference(notinbook, diff) unless diff.empty?