|
|
| Introduction | Variables | If-else |
| Strings | Functions | while-loop |
| For-Loop | List | Set |
| Dictionary | Tuple | Try..Except |
| Class/Object | Inheritance | Polymorphism |
| File Handling | ||
Reading the contents of a file and writing data to a file are important file handling concepts.
They are essential in Python applications. Python has several methods for creating, reading, updating, and deleting files.
The open() function is very useful in Python file-handling. It takes two parafile-handling meters
a) Name of the file
b) The mode in which the file needs to be opened (read, write, append, create)
There are four different methods (modes) for opening a file:
"r" - Opens a file for reading, error if the file does not exist. (Read)
"a" - Opens a file for appending. It creates the file if it does not exist. (Append)
"w" - Opens a file for writing. It creates the file if it does not exist. (Write)
"x" - Creates the specified file. It returns an error if the file exists. (Create)
If you are trying to create a new file "myfile.txt" and it does not already exist, this code will create an empty file with that name. Raises an error if the file exists: If a file named "myfile.txt" already exists in the same location, Python will raise a FileExistsError. This prevents accidental overwriting of existing files. Best practice with with statement: Using the with statement ensures that the file is automatically closed after the block of code is executed, even if errors occur.
Code Example 1:
#Creating a File to write.
try:
with open("myfile.txt", "x") as f:
f.write("This is a new file.")
print("File 'myfile.txt' created successfully.")
except FileExistsError:
print("Error: File 'myfile.txt' already exists.")
#Output:
File 'myfile.txt' created successfully.
To read the entire contents of a file in Python, using the with open() statement for proper file handling, you can use the read() method. Python
Code Example 2:
#Read the entire file.
with open("myfile.txt", "r") as f:
file_contents = f.read()
print(file_contents)
#Output:
These are the contents of the file.
This mode is used when you want to add new content to the end of an existing file without deleting its current contents. If the file "myfile.txt" does not exist, it will be created. File Pointer Position: When opened in append mode, the file pointer is automatically placed at the end of the file, ready for new data to be written.
Code Example 3:
#Append lines to existing file.
# Open the file in append mode
with open("myfile.txt", "a") as file:
# Write new content to the end of the file
file.write("This is a new line appended to the file.\n")
file.write("Another line added.\n")
#You can then read the file to see the appended content
with open("myfile.txt", "r") as file:
content = file.read()
print(content)
This mode is used when you want to add new content to the end of an existing file without deleting its current contents. If the file "myfile.txt" does not exist, it will be created. File Pointer Position: When opened in append mode, the file pointer is automatically placed at the end of the file, ready for new data to be written.
Code Example 3:
"""
Write lines to file.
Open the file in append mode
Open the file in write mode ("w")
If "myfile.txt" does not exist, it will be created.
If "myfile.txt" already exists,
its content will be truncated (emptied)
before new content is written.
"""
with open("myfile.txt", "w") as file_object:
# Write a string to the file
file_object.write("This is the first line.\n")
# Write another string to the file
file_object.write("This is the second line.\n")
file_object.write("And this is the third line.")
#The file is automatically closed when exiting the 'with' block.