1. 파일 쓰기(Writing to a File)
루비에서 파일에 데이터를 쓰기 위해 File.open 메서드를 사용합니다. 모드에 따라 파일을 생성하고 내용을 쓸 수 있습니다. "w" 모드는 파일을 새로 만들거나 기존 파일을 덮어씁니다.
# 파일 쓰기
File.open('write-file-result.txt', "w") do |file|
file.puts("Hello World, Ruby!")
file.puts("File Write Studying!")
end
2. 파일 읽기 (Reading from a File)
파일에서 데이터를 읽기 위해서는 역시 File.open 메서드를 사용합니다. 읽기 모드로 열면 파일의 내용을 읽을 수 있습니다. "r" 모드는 파일을 읽기 전용으로 읽습니다.
# 파일에서 읽기
File.open("write-file-result.txt", "r") do |file|
file.each_line do |line|
puts line
end
end
3. 파일 존재 여부 확인
파일이 존재하는지 확인하기 위해서는 File.exist? 메서드를 사용할 수 있습니다.
if File.exist?("write-file-result.txt")
puts "파일이 존재합니다!"
else
puts "파일이 존재하지 않습니다."
end
4. 파일 내용 전체 읽기
파일의 내용을 한 번에 모두 읽고 싶다면 File.read 메서드를 사용할 수 있습니다.
content = File.read("write-file-result.txt")
puts content
5. 파일 추가 (Appending to a File)
기존 파일에 내요을 추가하려면 "a" 모드를 사용할 수 있습니다. "a"모드를 사용해 파일 끝에 새로운 내용을 추가합니다.
# 파일에 추가하기
File.open("write-file-result.txt", "a") do |file|
file.puts("추가된 내용")
end
GitHub - set-up-init/ruby-tutorial-tistory: https://thinky.tistory.com/category/Back-End/Ruby
https://thinky.tistory.com/category/Back-End/Ruby. Contribute to set-up-init/ruby-tutorial-tistory development by creating an account on GitHub.
github.com
LIST
'Back-End > Ruby' 카테고리의 다른 글
[Ruby] 9장(완) 루비 고급 주제 (0) | 2025.03.15 |
---|---|
[Ruby] 8장 예외처리 (0) | 2025.03.12 |
[Ruby] 6장 모듈과 믹스인 (0) | 2025.03.07 |
[Ruby] 5장 클래스와 객체 지향 프로그래밍 (0) | 2025.03.01 |
[Ruby] 4장 함수 및 메서드 (0) | 2025.02.26 |