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 firstn
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