📚 File Handling: Reading and Writing Operations & Common Techniques | 文件处理:读写操作与常见技巧
File handling is an essential topic in computer science. It allows programs to store data permanently and retrieve it when needed. In this article, we will explore the core concepts of reading from and writing to files, as well as common techniques for effective file management.
文件处理是计算机科学中的一个重要主题。它允许程序永久存储数据并在需要时检索数据。在本文中,我们将探讨文件读取与写入的核心概念,以及有效管理文件的常见技巧。
1. Introduction to File Handling | 文件处理简介
Files provide a way to store data on secondary storage devices such as hard disks, SSDs, or USB drives. Unlike memory, data stored in files persists after the program terminates.
文件提供了一种将数据存储到辅助存储设备(如硬盘、固态硬盘或U盘)上的方式。与内存不同,存储在文件中的数据在程序终止后仍然存在。
File handling involves three main steps: opening the file, performing read or write operations, and closing the file. Understanding these steps is fundamental for building reliable applications.
文件处理包括三个主要步骤:打开文件、执行读取或写入操作、以及关闭文件。理解这些步骤是构建可靠应用程序的基础。
2. File Types: Text and Binary | 文件类型:文本与二进制
Files can be broadly classified into two types: text files and binary files. Text files contain human-readable characters encoded using a scheme such as ASCII or UTF-8. Binary files contain data in the form of bytes, which may not be directly readable as text.
文件大致可分为两类:文本文件和二进制文件。文本文件包含使用ASCII或UTF-8等方案编码的人类可读字符。二进制文件以字节形式存储数据,可能无法直接作为文本读取。
Examples of text files include .txt, .csv, .html, and .json files. Examples of binary files include images, audio, video, and compiled programs. The choice of file type affects how data is read and written.
文本文件的例子包括 .txt、.csv、.html 和 .json 文件。二进制文件的例子包括图像、音频、视频和编译后的程序。文件类型的选择会影响数据的读写方式。
A file pointer indicates the current position in the file. It moves after each read or write operation, and it can be manipulated using commands such as seek and tell.
文件指针指示文件中的当前位置。每次读取或写入操作后指针都会移动,并且可以通过 seek 和 tell 等命令进行操作。
3. Opening Files and File Modes | 打开文件与文件模式
Before any operation can be performed on a file, it must be opened. The mode passed to the open function determines whether the file is opened for reading, writing, appending, or both.
在对文件执行任何操作之前,必须先打开文件。传递给 open 函数的模式决定了文件是以读取、写入、追加还是读写方式打开。
The table below shows common file modes used in many programming languages, especially Python and pseudocode.
下表展示了在许多编程语言(尤其是Python和伪代码)中常用的文件模式。
| Mode | Description | 模式说明 |
|---|---|---|
| r | Open for reading. The file must exist. | 以读取方式打开。文件必须存在。 |
| w | Open for writing. Creates a new file or truncates the existing one. | 以写入方式打开。创建新文件或清空已有文件。 |
| a | Open for appending. Writes data to the end of the file. | 以追加方式打开。将数据写入文件末尾。 |
| r+ | Open for reading and writing. The file must exist. | 以读写方式打开。文件必须存在。 |
| rb / wb | Open for reading / writing in binary mode. | 以二进制模式打开进行读取或写入。 |
In Python, the syntax is: open(“filename”, “mode”). The file object returned by open supports methods such as read(), write(), and close().
在Python中,语法是:open(“filename”, “mode”)。open 返回的文件对象支持 read()、write() 和 close() 等方法。
4. Reading Text Files | 读取文本文件
Once a file is open for reading, its contents can be retrieved in several ways. The most common methods are read(), readline(), and readlines().
一旦文件以读取方式打开,可以通过多种方式获取其内容。最常见的方法是 read()、readline() 和 readlines()。
The read() method reads the entire file as a single string. If a number is provided, it reads that many characters.
read() 方法将整个文件作为一个字符串读取。如果提供了数字,则读取指定数量的字符。
The readline() method reads one line at a time, including the newline character at the end. It is useful for processing a file line by line without loading the whole file into memory.
readline() 方法每次读取一行,包括行尾的换行符。它适用于逐行处理文件,而无需将整个文件加载到内存中。
The readlines() method returns a list of strings, where each element is one line of the file. This is convenient when you need to access lines by their index, but it may consume a lot of memory for large files.
readlines() 方法返回一个字符串列表,其中每个元素是文件中的一行。这在需要按索引访问行时很方便,但对于大文件可能会消耗大量内存。
Example in Python:
Python示例:
file = open(“data.txt”, “r”)
content = file.read()
file.close()
It is important to close the file after reading to release system resources.
读取后关闭文件以释放系统资源非常重要。
5. Writing and Appending Text | 写入和追加文本
Writing to a file is a common operation. The write() method writes a string to the file. If the file was opened in w mode, its previous contents are erased before the new data is written.
向文件写入操作是常见操作。write() 方法向文件写入一个字符串。如果文件是以 w 模式打开的,则在写入新数据之前会清除文件原有的内容。
To add data to the end of an existing file without erasing its contents, use the a (append) mode. The write() method can be called repeatedly to write multiple strings.
要在不清除原内容的情况下向已有文件的末尾添加数据,请使用 a(追加)模式。可以重复调用 write() 方法来写入多个字符串。
Python also provides writelines() which accepts a list of strings and writes them in sequence. Note that writelines does not automatically add newline characters.
Python还提供了 writelines(),它接受一个字符串列表并按顺序写入。注意 writelines 不会自动添加换行符。
file = open(“output.txt”, “w”)
file.write(“Hello\n”)
file.close()
When using w mode with an existing file, the file is truncated first. Therefore, be cautious because this may cause data loss if the file is important.
当对已有文件使用 w 模式时,文件会被先截断。因此要小心,因为如果文件重要,这可能会导致数据丢失。
6. Closing Files and Resource Management | 关闭文件与资源管理
Closing a file is essential to ensure that all data is flushed to disk and that system resources are freed. If a program exits without closing a file, data written with write() might not be saved properly.
关闭文件对于确保所有数据刷新到磁盘并释放系统资源至关重要。如果程序在未关闭文件的情况下退出,使用 write() 写入的数据可能无法正确保存。
In Python, the with statement is the recommended way to manage files. It automatically closes the file when the block exits, even if an exception occurs.
在Python中,with 语句是管理文件的推荐方式。当代码块退出时,它会自动关闭文件,即使发生异常也是如此。
with open(“data.txt”, “r”) as file:
content = file.read()
Using with is considered a best practice because it prevents resource leaks and makes the code cleaner and more robust.
使用 with 被认为是最佳实践,因为它可以防止资源泄漏,并使代码更简洁、更健壮。
7. File Pointers and Seeking | 文件指针与定位
Every open file has an internal pointer that records the position where the next read or write will occur. This pointer moves automatically as data is read or written.
每个打开的文件都有一个内部指针,记录下一次读取或写入将发生的位置。在读取或写入数据时,该指针会自动移动。
The tell() method returns the current position of the file pointer, measured in bytes from the beginning of the file. The seek() method moves the pointer to a specified position.
tell() 方法返回文件指针的当前位置,以距文件开头的字节数计算。seek() 方法将指针移动到指定位置。
For example, to move to the 10th byte of a file, you can use file.seek(10). To move to the end of the file, you can use file.seek(0, 2), where 2 indicates the end of the file.
例如,要移动到文件的第10个字节,可以使用 file.seek(10)。要移动到文件末尾,可以使用 file.seek(0, 2),其中 2 表示文件末尾。
File pointer manipulation is particularly useful when you need to overwrite specific sections of a file or when reading large files in chunks.
文件指针操作在需要覆盖文件的特定部分或分块读取大文件时特别有用。
8. Handling Errors and Exceptions | 错误处理与异常
File operations often fail due to missing files, incorrect permissions, or invalid modes. Proper error handling is necessary to avoid program crashes and to provide meaningful feedback to users.
文件操作常常会因为文件不存在、权限不正确或模式无效而失败。适当的错误处理是必要的,以避免程序崩溃并为用户提供有意义的反馈。
Common exceptions in Python include FileNotFoundError, PermissionError, IsADirectoryError, and UnicodeDecodeError. Using try-except blocks allows the program to respond gracefully.
Python中常见的异常包括 FileNotFoundError、PermissionError、IsADirectoryError 和 UnicodeDecodeError。使用 try-except 块可以使程序优雅地作出响应。
try:
file = open(“missing.txt”, “r”)
except FileNotFoundError:
print(“File not found.”)
In addition to exceptions, it is also important to check whether a file exists before opening it. Python’s os.path.exists() or pathlib.Path.is_file() can be used for this purpose.
除了异常之外,在打开文件前检查文件是否存在也很重要。可以使用Python的 os.path.exists() 或 pathlib.Path.is_file() 来实现这一点。
9. Working with CSV Files | 处理CSV文件
CSV (Comma-Separated Values) files are a common format for storing tabular data. Each line represents a record, and fields are separated by commas.
CSV(逗号分隔值)文件是存储表格数据的常见格式。每行表示一条记录,字段用逗号分隔。
In Python, the csv module provides functions for reading and writing CSV files efficiently. csv.reader() returns a reader object that iterates over lines as lists of fields.
在Python中,csv 模块提供了高效读写CSV文件的函数。csv.reader() 返回一个 reader 对象,该对象将每一行迭代为字段列表。
When reading a CSV file, you can use a for loop to process each record. It is often necessary to skip the header row before processing the data.
读取CSV文件时,可以使用 for 循环处理每条记录。通常需要在处理数据前跳过标题行。
To write data to a CSV file, use csv.writer() and its writerow() method. This method automatically handles comma separation and newline characters.
要向CSV文件写入数据,请使用 csv.writer() 及其 writerow() 方法。该方法会自动处理逗号分隔和换行符。
import csv
with open(“data.csv”, “w”, newline=”) as file:
writer = csv.writer(file)
writer.writerow([“Name”, “Score”])
10. Working with Binary Files | 处理二进制文件
Binary files store data in a format that is not meant to be read as text. They are used for images, sound files, serialised objects, and compiled programs.
二进制文件以一种并非用于文本读取的格式存储数据。它们用于图像、声音文件、序列化对象和编译程序。
In Python, binary files are opened with modes such as “rb” or “wb”. The read() method returns a bytes object, and the write() method accepts a bytes-like object.
在Python中,二进制文件以 “rb” 或 “wb” 等模式打开。read() 方法返回一个 bytes 对象,write() 方法接受 bytes 类的对象。
Unlike text files, binary files do not apply any encoding or decoding. This makes them more compact and faster to process, but also harder for humans to inspect.
与文本文件不同,二进制文件不进行任何编码或解码。这使得它们更紧凑、处理速度更快,但也更难供人检查。
One common use of binary files is to save structured data using the pickle module. However, pickle files are specific to Python and should not be shared across different systems without caution.
二进制文件的一种常见用途是使用 pickle 模块保存结构化数据。但是,pickle 文件是Python特有的,不应随意在不同系统之间共享。
11. Common Techniques and Best Practices | 常见技巧与最佳实践
Several techniques can improve file handling efficiency and reliability. Here are some important recommendations for examinations and real-world programming.
有几种技术可以提高文件处理的效率和可靠性。以下是针对考试和实际编程的一些重要建议。
-
Always close files: use the with statement or close() to release resources.
始终关闭文件:使用 with 语句或 close() 释放资源。
-
Use appropriate modes: choose r, w, or a based on whether you need to read, overwrite, or append.
使用适当的模式:根据需要读取、覆盖还是追加,选择 r、w 或 a。
-
Read large files line by line instead of loading the entire file into memory.
逐行读取大文件,而不是将整个文件加载到内存中。
-
Handle exceptions to make the program robust against missing or corrupt files.
处理异常,使程序对缺失或损坏的文件具有鲁棒性。
-
Specify the correct encoding (e.g., utf-8) when opening text files to avoid character errors.
打开文本文件时指定正确的编码(例如 utf-8),以避免字符错误。
-
Use absolute paths when the current working directory is unclear, but be aware that relative paths are more portable.
当当前工作目录不明确时使用绝对路径,但要注意相对路径更具可移植性。
Following these practices will help you write clean, efficient, and maintainable file handling code.
遵循这些实践将帮助您编写清晰、高效且可维护的文件处理代码。
12. Summary | 总结
File handling is a fundamental skill in computer science. It involves opening files with the correct mode, performing read or write operations, and closing files properly.
文件处理是计算机科学中的一项基本技能。它涉及以正确的模式打开文件、执行读取或写入操作,并正确关闭文件。
Key methods include read(), readline(), readlines() for input, and write(), writelines() for output. File modes such as r, w, and a control how the file is accessed.
关键方法包括用于输入的 read()、readline()、readlines(),以及用于输出的 write()、writelines()。r、w 和 a 等文件模式控制访问文件的方式。
Advanced topics such as file pointers, error handling, CSV files, and binary files extend the applicability of file handling in real-world projects. Mastering these concepts is also essential for CIE Computer Science examinations.
文件指针、错误处理、CSV文件和二进制文件等高级主题扩展了文件处理在实际项目中的适用性。掌握这些概念对于CIE计算机科学考试也至关重要。
By following best practices like using the with statement and handling exceptions, you can build robust applications that manage data safely and efficiently.
通过遵循使用 with 语句和处理异常等最佳实践,您可以构建安全、高效管理数据的健壮应用程序。
Published by TutorHao | Computer Science Revision Series | aleveler.com
更多咨询请联系16621398022(同微信)
屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导Cancel reply