Reading and Writing Files
Interacting with files is a fundamental aspect of programming, especially in automation and data processing tasks. Python provides robust capabilities to manipulate files and directories, making it a powerful tool for IT specialists and system administrators.
File Systems Overview
Operating systems like Windows, macOS, and Linux use file systems to organize data storage and access. Data is stored in files within containers called directories or folders. These are structured hierarchically in a tree format.
Paths in File Systems
- Absolute Path: Specifies the complete path to a file or directory from the root of the file system.
- Windows Example:
C:\Users\Jordan - Linux Example:
/home/jordan
- Windows Example:
- Relative Path: Specifies a path relative to the current working directory.
- Example: If the current directory is
/home/jordan, the relative pathexamplesrefers to/home/jordan/examples.
- Example: If the current directory is
Understanding paths is crucial when writing scripts that interact with the file system, as it determines how resources are located and accessed.
Reading Files
Python allows you to read files using built-in functions and methods, enabling efficient data processing.
Opening Files
Use the open() function to open a file and create a file object:
file = open("spider.txt")
- By default, files are opened in read-only mode (
"r"). - The
open()function checks for the file's existence and permissions.
Reading Methods
readline()
Reads a single line from the file:
print(file.readline())
print(file.readline())
read()
Reads the entire file from the current position to the end:
print(file.read())
Iterating Over Files
You can iterate over each line in the file:
with open("spider.txt") as file:
for line in file:
print(line)
Handling Newlines
Lines read from a file include the newline character (\n):
-
This can cause extra blank lines when printing.
-
Use
strip()to remove surrounding whitespace:with open("spider.txt") as file:for line in file:print(line.strip())
Closing Files
Always close files to free up resources:
file.close()
-
Using a
withstatement ensures the file is automatically closed:with open("spider.txt") as file:# File operations
Iterating Through Files
Processing files line by line is essential for handling large datasets efficiently.
Reading Lines into a List
Use readlines() to read all lines into a list:
with open("spider.txt") as file:
lines = file.readlines()
-
You can then manipulate the list, such as sorting:
lines.sort()print(lines)