← Back to Ruby Course | Chapter 11: File I/O & Exceptions | Lesson 1 of 6

File.read और File.write

File.read एक file खोलता है और आपको इसका सारा text देता है, और File.write एक file में text save करता है। यह एक पूरी letter पढ़ने या एक नई लिखने जैसा है।
Syntax
ruby
content = File.read("path")
File.write("path", content)

File.read और File.write

File.read("path") एक call में एक पूरी file का content एक single string में पढ़ता है, एक छोटी-मध्यम text file load करने का सबसे simple तरीका।

File.write("path", content) एक string को एक file में लिखता है, इसे बनाते या overwrite करते हुए। दोनों simple, one-shot file operations के लिए convenient class-level methods हैं।

Note: File.write default से पूरी file overwrite करता है -- extra options के बिना कोई separate append mode नहीं है।

उदाहरण: File.read and File.write

markup
File.write("greeting.txt", "Hello from File.write!")

content = File.read("greeting.txt")
puts content
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक ऐसी file पढ़ना जो exist नहीं करती, जो Errno::ENOENT raise करता है।
  2. यह उम्मीद करना कि File.write append करेगा, जब यह file का content overwrite करता है।
  3. एक relative path इस्तेमाल करना और गलत folder में file ढूंढना, क्योंकि यह working directory के relative है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.