Reading and Writing Text and Numbers from/to a File
Reading Text Files in Python
Python provides several methods to read the contents of a text file.
Opening a File
The first step is to open the file using the open() function. The function takes two arguments: the
filename and the mode. The most common mode for reading is 'r'.
Python
with open('my_file.txt', 'r') as file: # Perform file operations hereThe with statement ensures proper closing of the file even if an exception
occurs.
Reading Methods
There are three primary methods to read the contents of a file:
1. read()
Reads the entire contents of the file as a single string.
Python
with open('my_file.txt', 'r') as file: content = file.read() print(content)2. readline()
Reads a single line from the file.
Python
with open('my_file.txt', 'r') as file: line = file.readline() print(line)3. readlines()
Reads all lines of the file and returns them as a list of strings.
Python
with open('my_file.txt', 'r') as file: lines = file.readlines() for line in lines: print(line, end='')Additional Considerations
·
Encoding: If you know the character
encoding of the file, you can specify it using the encoding parameter in the open() function.
·
Error
handling:
Use try-except blocks to handle potential
errors like file not found or permission denied.
·
Large
files:
For large files, consider reading the file in chunks using read(size) to avoid loading the entire file into memory.
Example:
Python
with open('my_file.txt', 'r', encoding='utf-8') as file: for line in file: line = line.strip() # Remove leading/trailing whitespace if line: # Skip empty lines print(line)By understanding these methods and considerations, you can effectively read text files in your Python applications.
Writing to a Text File in Python
Opening a File for Writing
To write to a text file in Python, you'll use the open() function with the 'w' mode (write) or 'a'
mode (append).
·
'w': Overwrites the entire file
if it exists or creates a new file if it doesn't.
·
'a': Appends data to the end of
the file, creating the file if it doesn't exist.
Python
with open('my_file.txt', 'w') as file: # Write to the fileWriting to the File
Use the write() method to write
strings to the file:
Python
with open('my_file.txt', 'w') as file: file.write("This is the first line.\n") file.write("This is the second line.\n")
Writing Multiple Lines
You can write multiple lines using a loop or by
creating a list of strings and using the writelines() method:
Python
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]with open('my_file.txt', 'w') as file: file.writelines(lines)Important Considerations
·
Encoding: Specify the encoding if
needed using the encoding parameter in the open() function.
·
Error
Handling:
Use try-except blocks to handle potential
errors like file not found or permission denied.
·
Closing
the File:
The with statement automatically closes the file, but
you can also use file.close() explicitly.
Example
Python
import datetime with open('log.txt', 'a') as file: now = datetime.datetime.now() file.write(f"{now}: Something happened.\n")This code appends a timestamped message to an existing log file.
Deleting a File
To delete a file in Python, you'll use the os module's remove() function. However, it's essential to check if the file exists before
attempting to delete it to avoid errors.
Python
import os def delete_file_if_exists(file_path): """Deletes a file if it exists.""" if os.path.exists(file_path): os.remove(file_path) print(f"File '{file_path}' deleted successfully.") else: print(f"File '{file_path}' not found.") # Example usage:file_to_delete = "my_file.txt"delete_file_if_exists(file_to_delete)Explanation:
1.
Import
the os module: This module provides functions for interacting
with the operating system.
2.
Define
a function: The delete_file_if_exists function takes the file
path as input.
3.
Check
file existence: Use os.path.exists() to verify if the file
exists.
4.
Delete
the file:
If the file exists, use os.remove() to delete it.
5. Handle non-existent file: If the file doesn't exist, print a message indicating so.
Key points:
· Always check for file existence before deletion to avoid errors.
·
Use os.path.exists() to verify file existence.
·
Employ os.remove() to delete the file.
· Provide informative messages for success or failure.
By following these steps, you can safely delete files in your Python scripts without encountering errors.