Learn Python variables with this beginner-friendly guide. Understand variable naming rules, assignments, and operations with examples and exercises. Perfect for students and professionals starting their Python journey.
open() function.r), write (w), and append (a).#### Reading a File:
open() with mode 'r' to read from a file..read() to read the entire file or .readlines() to read the file line by line.Example of reading a file:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
#### Writing to a File:
open() with mode 'w' to write to a file. This will overwrite the file if it exists.'a' to append content to an existing file.Example of writing to a file:
with open('example.txt', 'w') as file:
file.write("Hello, this is a test file.\n")
file.write("Python makes file handling easy.")
### 2. Handling File Exceptions
try and except block to handle these exceptions.Example:
try:
with open('nonexistent_file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("The file was not found.")
input() function to capture user input.input() returns a string, so you may need to convert it to another data type (e.g., int() or float()).Example:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello {name}, you are {age} years old.")
Example:
user_input = input("Enter some text to save to the file: ")
with open('user_input.txt', 'w') as file:
file.write(user_input)