Python Tutorial: open() function for beginners

Veröffentlicht am: 29 Juni 2024
auf dem Kanal: Ferds Tech Channel
707
7

In this video, I will talk about the built-in open function in python.

The open() function in Python is a built-in function that opens a file and returns it as a file object.
With this file object, you can read, create, update, and delete files.
Here are some commonly-used modes for opening files:
'r': open for reading (default)
'w': open for writing, truncating the file first
'a': open for writing, appending to the end of file if it exists.
'x': open for exclusive creation, failing if the file already exists

1. Reading from a File ("sample.txt", "r" mode)
file = open("sample.txt", "r") # Open the file in read mode
content = file.read() # Read the entire content of the file
print(content) # Print the content to the console
file.close() # Close the file

2. Read all lines from the file
Open the file for writing
file = open("sample_lines.txt", "w")

Write sample lines to the file
file.write("Line 1\n")
file.write("Line 2\n")
file.write("Line 3\n")

Close the file
file.close()

Open the file for reading
file = open("sample_lines.txt", "r")

Read all lines from the file
lines = file.readlines()

Close the file
file.close()

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


3. Appending to a File ("log.txt", "a" mode)
file = open("log.txt", "a") # Open or create the file in append mode
file.write("New log entry: Something happened!\n") # Append the log entry
file.write("Another log entry: Something happened!\n")
file.close() # Close the file

4. Writing to a File ("output.txt", "w" mode)
file = open("output.txt", "w") # Open or create the file in write mode
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."
file.write("This is another line.") # Write "This is a new line."
file.close() # Close the file

5. Creating a New File ("new_file.txt", "x" mode)
try:
file = open("new_file.txt", "x") # Attempt to create a new file
file.write("This is a new file.") # Write to the newly created file
file.close() # Close the 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()

#python #pythontutorial #pythonforbeginners


Auf dieser Seite können Sie das Online-Video Python Tutorial: open() function for beginners mit der Dauer online in guter Qualität ansehen, das der Benutzer Ferds Tech Channel 29 Juni 2024 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 707 Mal angesehen und es wurde von 7 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!