Python Tutorial: open() within the with statement for beginners

Опубликовано: 04 Октябрь 2024
на канале: Ferds Tech Channel
59
2

In this video, I will cover the python "with block".

The with statement in Python is a concise way to manage resources, such as files or network connections.
It ensures proper setup and cleanup, making code more readable and robust.
When used with file handling, it automatically closes the file when the associated block of code exits.

1. Reading from a File.
with open("sample.txt", "r") as file:
content = file.read() # Read the entire content of the file
print(content) # Print the content to the console

2. Reading all lines from a file
Create a sample text file with multiple lines
with open("sample_lines.txt", "w") as file:
file.write("Line 1\n")
file.write("Line 2\n")
file.write("Line 3\n")

with open("sample_lines.txt", "r") as file:
lines = file.readlines() # Read all lines from the file

Print each line
for line in lines:
print(line.strip()) # Remove trailing newline character

3. Appending to a File ("log.txt", "a" mode)
with open("log.txt", "a") as file:
file.write("New log entry: Something happened!\n") # Append the log entry

4. Writing to a File ("output.txt", "w" mode)
with open("output.txt", "w") as file:
file.write("Hello, world!\n") # Write "Hello, world!" followed by a newline
file.write("This is a new line.") # Write "This is a new line."

5. Creating a New File ("new_file.txt", "x" mode)
try:
with open("new_file.txt", "x") as file: # Creating a New File
file.write("This is a new file.") # Write to the newly created file
except FileExistsError:
print("File already exists!") # Handle the exception if the file exists

6a. Deleting a file using the os module
import os # Import the os module for file operations

Specify the file path
file_path = "sample.txt"

Check if the file exists before attempting to delete it
if os.path.isfile(file_path):
os.remove(file_path) # Delete the file
print(f"{file_path} has been deleted.")
else:
print(f"Error: {file_path} not found.") # Print an error message

6b. Deleting a file using the pathlib module
from pathlib import Path # Import the Path class from the pathlib module

Create a Path object for the file you want to delete
file_path = Path('path_to_your_file.txt')

Check if the file exists
if file_path.exists():
If the file exists, delete it
file_path.unlink()

#pythonforbeginners #pythontutorial #python