IT박스

Ruby에서 파일에 쓰는 방법?

itboxs 2020. 10. 4. 10:46
반응형

Ruby에서 파일에 쓰는 방법?


데이터베이스에서 데이터를 읽어서 텍스트 파일에 저장해야합니다.

Ruby에서 어떻게 할 수 있습니까? Ruby에 파일 관리 시스템이 있습니까?


루비의 파일 클래스는 당신에게 기능과의 아웃 줄 것이다 ::new::open하지만 부모의 IO 클래스 의 깊이에, 도착을 #read하고 #write.


다음을 찾고 계십니까?

File.open(yourfile, 'w') { |file| file.write("your text") }

짧은 버전을 사용할 수 있습니다.

File.write('/path/to/file', 'Some glorious content')

쓰여진 길이를 반환합니다. 자세한 내용과 옵션 :: write 를 참조하십시오.

파일에 추가하려면 이미있는 경우 다음을 사용하십시오.

File.write('/path/to/file', 'Some glorious content', mode: 'a')

이는 대부분의 경우 선호되는 접근 방식입니다.

 File.open(yourfile, 'w') { |file| file.write("your text") }

블록이에 전달되면 블록이 File.open종료 될 때 File 객체가 자동으로 닫힙니다.

에 블록을 전달하지 않으면 File.open파일이 올바르게 닫히고 내용이 파일에 기록되었는지 확인해야합니다.

begin
  file = File.open("/tmp/some_file", "w")
  file.write("your text") 
rescue IOError => e
  #some error occur, dir not writable etc.
ensure
  file.close unless file.nil?
end

문서 에서 찾을 수 있습니다 .

static VALUE rb_io_s_open(int argc, VALUE *argv, VALUE klass)
{
    VALUE io = rb_class_new_instance(argc, argv, klass);
    if (rb_block_given_p()) {
        return rb_ensure(rb_yield, io, io_close, io);
    }
    return io;
}

여기에서 찾은 Zambri 의 대답 이 최고입니다.

File.open("out.txt", '<OPTION>') {|f| f.write("write your stuff here") }

귀하의 옵션 <OPTION>은 다음과 같습니다.

r-읽기 전용. 파일이 있어야합니다.

w -쓰기 위해 빈 파일을 만듭니다.

a -Append to a file. 파일이 없으면 생성됩니다.

r+-읽기와 쓰기 모두 업데이트 할 파일을 엽니 다. 파일이 있어야합니다.

w+ -읽기와 쓰기를 위해 빈 파일을 만듭니다.

a+-읽고 추가 할 파일을 엽니 다. 파일이없는 경우 생성됩니다.

귀하의 경우 w에는 바람직합니다.


모범으로 배우는 사람들을 위해 ...

다음과 같은 파일에 텍스트를 씁니다.

IO.write('/tmp/msg.txt', 'hi')

보너스 정보 ...

다음과 같이 다시 읽으십시오.

IO.read('/tmp/msg.txt')

Frequently, I want to read a file into my clipboard ***

Clipboard.copy IO.read('/tmp/msg.txt')

And other times, I want to write what's in my clipboard to a file ***

IO.write('/tmp/msg.txt', Clipboard.paste)

*** Assumes you have the clipboard gem installed

See: https://rubygems.org/gems/clipboard


To destroy the previous contents of the file, then write a new string to the file:

open('myfile.txt', 'w') { |f| f << "some text or data structures..." } 

To append to a file without overwriting its old contents:

open('myfile.txt', "a") { |f| f << 'I am appended string' } 

참고URL : https://stackoverflow.com/questions/2777802/how-to-write-to-file-in-ruby

반응형