Video není dostupné.
Omlouváme se.

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

Sdílet
Vložit
  • čas přidán 19. 08. 2024
  • 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
    ")
    file.write("Line 2
    ")
    file.write("Line 3
    ")
    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!
    ") # Append the log entry
    4. Writing to a File ("output.txt", "w" mode)
    with open("output.txt", "w") as file:
    file.write("Hello, world!
    ") # 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

Komentáře •