Python provides powerful tools for file handling and managing standard output (STDOUT) using the print() function.


๐Ÿ”น File Handling in Python

Python allows us to read, write, and manipulate files using the built-in open() function.

๐Ÿ“Œ Syntax of open()

file = open("filename", mode)
Mode Description
'r' Read (default), raises an error if the file doesnโ€™t exist
'w' Write (creates a new file or overwrites an existing file)
'a' Append (adds content at the end of the file)
'x' Create (creates a new file, fails if the file exists)
'b' Binary mode (e.g., images, videos: 'rb', 'wb')

๐Ÿ”น Writing to a File

# Open the file in write mode ('w')
file = open("example.txt", "w")

# Write to the file
file.write("Hello, this is a test file.\n")
file.write("Python file handling is easy!\n")

# Close the file
file.close()

๐Ÿ”น Note: 'w' mode overwrites the file if it already exists.


๐Ÿ”น Reading from a File

file = open("example.txt", "r")  # Open in read mode
content = file.read()  # Read the entire file
print(content)  # Output file content to STDOUT
file.close()

๐Ÿ”น Alternative Methods to Read:

  • read(n): Reads the first n characters.
  • readline(): Reads one line at a time.
  • readlines(): Reads all lines as a list.
with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())  # Print each line without extra newlines

๐Ÿ”น Using with open() automatically closes the file after use.


๐Ÿ”น Appending to a File

with open("example.txt", "a") as file:
    file.write("This is an additional line.\n")

๐Ÿ”น Appending does not overwrite existing content.


๐Ÿ”น Checking if a File Exists

import os

if os.path.exists("example.txt"):
    print("File exists!")
else:
    print("File not found!")

๐Ÿ”น Sending Output to STDOUT using print()

By default, print() outputs to Standard Output (STDOUT), which is the console.

print("Hello, World!")  # Output: Hello, World!

๐Ÿ“Œ Redirecting Output to a File

We can redirect print() output to a file instead of the console.

with open("output.txt", "w") as file:
    print("This will be written to the file.", file=file)

๐Ÿ”น Now, the message is saved in output.txt instead of printing to the screen.


๐Ÿ”น Writing Output to Both STDOUT and a File

import sys

# Open file for writing
file = open("log.txt", "w")

# Print to both STDOUT and file
print("Logging information...", file=file)  # To file
print("Logging information...", file=sys.stdout)  # To STDOUT

file.close()

๐Ÿ”น sys.stdout ensures output still appears on the screen.


๐Ÿ”น Redirecting STDOUT to a File

If you want to redirect all print statements to a file:

import sys

# Open a file for writing
sys.stdout = open("output.log", "w")

print("This message goes to the file, not the console!")
sys.stdout.close()

๐Ÿ”น After running this, the output will be in output.log instead of the console.


๐ŸŽฏ Summary

Feature Example
Write to file file.write("Hello")
Read from file file.read()
Append to file file.write("More content")
Print to STDOUT print("Hello, World!")
Redirect print() to file print("Message", file=open("file.txt", "w"))
Redirect all STDOUT to file sys.stdout = open("log.txt", "w")

Would you like a real-world example, like logging errors to a file? ๐Ÿš€


Leave a Reply

Your email address will not be published. Required fields are marked *