Reading from and
Writing to Files



Understanding File Input and Output

File I/O (Input/Output) is the process of reading data from a file and writing data to a file. Most programs interact with files to save data persistently—for example, saving user data, logs, configurations, or reports.

Why File I/O is Important

Files allow programs to:

Opening a File

Before performing any operation on a file, it must be opened using a file handler or reference.

// Open a file for reading
file = open("data.txt", mode="read")

// Open a file for writing (creates if not exists)
file = open("output.txt", mode="write")

// Open a file for appending (writes at end)
file = open("log.txt", mode="append")

Question: What happens if the file doesn't exist in reading mode?

Answer: It usually throws an error because reading expects the file to be present. Writing or appending mode can create the file if it doesn't exist.

Reading from a File

When reading, data is extracted from the file and loaded into memory. You can read:

// Read entire file content
content = file.readAll()

// Read one line
line = file.readLine()

// Read fixed number of characters
chunk = file.readChars(100)

Output:

Hello, this is a sample text file.
It has multiple lines of content.

Question: Why would you read line by line instead of the whole file?

Answer: Reading line-by-line is memory efficient for large files and allows processing content incrementally.

Writing to a File

Writing stores content into a file. Writing mode overwrites existing content, while append mode adds to the end.

// Write to file
file.write("This is a new file.")

// Append to existing file
file.append("New log entry recorded.")

Output:

This is a new file.
New log entry recorded.

Question: What if you open a file in write mode and it already has data?

Answer: It will overwrite the existing content unless opened in append mode.

Closing a File

Always close a file after completing operations to release system resources and ensure data is saved properly.

file.close()

Tip: Some languages provide automatic handling (like using blocks or context managers) to ensure files are closed, even if an error occurs.

Putting It All Together

// Complete flow to read and write
inputFile = open("input.txt", mode="read")
data = inputFile.readAll()
inputFile.close()

outputFile = open("result.txt", mode="write")
outputFile.write("Processed Data:\n" + data)
outputFile.close()

Output:

Processed Data:

Points to Remember



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M