2010-03-13 7 views
22

일부 검색 및 바꾸기를 수행하는 간단한 스크립트가 있습니다. 이 그것은 기본적으로 :Ruby - 스크립트 출력으로 새 파일을 작성하는 방법

File.open("us_cities.yml", "r+") do |file| 
    while line = file.gets 
    "do find a replace" 
    end 
    "Here I want to write to a new file" 
end 

당신은 내가 출력으로 새 파일을 작성하려면 볼 수 있듯이. 어떻게해야합니까? 귀하의 예제에서 그래서

output = File.open("outputfile.yml","w") 
output << "This is going to the output file" 
output.close 

,이 작업을 수행 할 수 있습니다 :

File.open("us_cities.yml", "r+") do |file| 
    while line = file.gets 
    "do find a replace" 
    end 
    output = File.open("outputfile.yml", "w") 
    output << "Here I am writing to a new file" 
    output.close  
end 

새 파일로 출력

답변

32

는 (두 번째 매개 변수를 잊지 마세요)이 같이 수행 할 수 있습니다 파일에 추가하려면 루프 밖에서 출력 파일의 열기를 넣어야합니다.

5

먼저 당신은

그런 다음 출력과 새로운 파일을 만들 것입니다

File.open("us_cities.yml", "r+") do |file| 
    new_file = File.new("newfile.txt", "r+") 
    while line = file.gets 
    new_file.puts "do find a replace" 
    end 
end 

이 스크립트를 변경 NEWFILE.TXT으로 새로운 파일을 생성해야

관련 문제