File Handling | 文件处理

📚 File Handling | 文件处理

This article explains file handling for the IGCSE Computer Science syllabus. We will look at why files are needed, the difference between text and binary files, and how to read from and write to files in a structured way.

本文面向 IGCSE 计算机科学考纲,讲解文件处理的核心知识。我们将探讨为什么需要文件、文本文件与二进制文件的区别,以及如何按规范读写文件。


1. Why Do We Need Files? | 我们为什么需要文件?

When a program runs, the data it uses is stored in main memory (RAM). However, RAM is volatile, which means it loses all data when the computer is turned off. To keep data permanently, we must store it in files on secondary storage such as a hard disk or solid-state drive.

程序运行时,其使用的数据存放在主存储器(内存)中。然而,内存是易失性存储器,计算机关闭时数据会全部丢失。为了永久保存数据,我们必须将数据以文件形式存储在硬盘或固态硬盘等辅助存储器上。

File handling is the set of techniques that allow a program to store data in a file and later retrieve that data. It makes data persistent and allows different programs to exchange information.

文件处理是让程序能够将数据存入文件并在之后取回数据的一整套技术。它使数据具有持久性,并允许不同程序之间交换信息。

  • Files survive power loss. | 文件在断电后仍然保留。
  • Files allow large amounts of data to be stored. | 文件可以存储大量数据。
  • Files let programs share data. | 文件让程序之间共享数据。
  • Files are essential for databases and record keeping. | 文件是数据库和记录保存的基础。

2. Text Files vs Binary Files | 文本文件与二进制文件

A text file stores data as a sequence of characters. Each character is encoded using a scheme such as ASCII or Unicode. A text file can be opened and viewed in a normal editor and is easy for humans to read.

文本文件以字符序列的形式存储数据。每个字符都使用 ASCII 或 Unicode 等编码方案表示。文本文件可以用普通编辑器打开查看,人类很容易阅读。

A binary file stores data in the same way it is represented inside the computer, often as bytes. Binary files are not human-readable and may store numbers, images, sound, or executable code. They are more compact and faster to process, but less portable.

二进制文件以数据在计算机内部的表示形式存储,通常为字节。二进制文件无法直接阅读,可能存储数字、图像、声音或可执行代码。它们更紧凑、处理更快,但可移植性较差。

Text file | 文本文件 Binary file | 二进制文件
Human-readable | 人类可读 Not human-readable | 不可读
Uses ASCII/Unicode | 使用 ASCII/Unicode Uses raw bytes | 使用原始字节
Larger file size | 文件较大 Smaller file size | 文件较小
Examples: .txt, .csv, .html | 例如 .txt、.csv、.html Examples: .jpg, .mp3, .exe | 例如 .jpg、.mp3、.exe

3. File Access Modes | 文件访问模式

Before a file can be used, it must be opened. When opening a file, the program must state whether it will read, write, or append data. Different modes allow different operations.

在使用文件之前,必须先打开文件。打开文件时,程序必须说明是要读取、写入还是追加数据。不同的模式允许不同的操作。

  • Read mode (‘r’): opens an existing file for reading. | 读取模式(’r’):打开已有文件用于读取。
  • Write mode (‘w’): opens a file for writing. If the file exists, its old contents are deleted. | 写入模式(’w’):打开文件用于写入。如果文件已存在,旧内容会被删除。
  • Append mode (‘a’): opens a file for adding data at the end. Existing data is kept. | 追加模式(’a’):打开文件用于在末尾添加数据。已有数据得到保留。

open(file_name, mode) → file object | open(文件名, 模式) → 文件对象

It is important to choose the correct mode. Using write mode on an existing file will overwrite it, which may cause accidental loss of data.

选择正确的模式非常重要。对已有文件使用写入模式会覆盖原文件,可能导致意外数据丢失。


4. The Four Main File Operations | 四个主要文件操作

In the IGCSE syllabus, file handling is described with four essential operations: open, read, write, and close. Understanding these operations is critical for answering exam questions.

在 IGCSE 考纲中,文件处理包含四个基本操作:打开、读取、写入和关闭。理解这些操作对解答考试题目至关重要。

  1. Open: connects the program to the file and prepares it. | 打开:将程序与文件连接并准备就绪。
  2. Read: transfers data from the file into the program. | 读取:将数据从文件传输到程序中。
  3. Write: transfers data from the program into the file. | 写入:将数据从程序传输到文件中。
  4. Close: releases the file so other programs can use it. | 关闭:释放文件,使其他程序可以使用它。

Closing a file is especially important. If a file is left open when writing, some data may still be in a buffer and not yet saved to disk. Closing the file ensures that all data is written completely.

关闭文件尤其重要。如果写入后不关闭文件,部分数据可能仍停留在缓冲区中,尚未保存到磁盘。关闭文件可以确保所有数据都被完整写入。


5. Reading from a Text File | 从文本文件读取数据

When reading a text file, a program can read the whole file at once, read one line at a time, or read one character at a time. The approach depends on the amount of data and how the program needs to process it.

读取文本文件时,程序可以一次读取整个文件、一次读取一行或一次读取一个字符。采用哪种方式取决于数据量以及程序需要如何处理数据。

The typical loop structure for reading a text file is shown below in pseudocode:

OPEN FILE FOR READ
WHILE NOT EOF
READ LINE INTO variable
PROCESS variable
END WHILE
CLOSE FILE

EOF stands for “End Of File”. It is a special marker that shows when no more data remains in the file. The loop continues until EOF is reached.

EOF 代表 “End Of File”(文件末尾)。它是一个特殊标记,表示文件中不再有数据。循环持续运行直到到达 EOF。

  • Reading line by line is memory-efficient for large files. | 逐行读取对大文件而言节省内存。
  • Reading the whole file is simpler but uses more memory. | 一次性读取整个文件更简单,但占用更多内存。
  • Files must be closed after reading. | 读取后必须关闭文件。

6. Writing and Appending to a File | 写入与追加到文件

Writing to a file places new data into the file. In write mode, the file is created if it does not exist, and overwritten if it does. In append mode, new data is added at the end of the existing content.

写入文件就是把新数据放入文件中。在写入模式下,如果文件不存在则会创建文件;如果文件已存在则会被覆盖。在追加模式下,新数据会被添加到已有内容的末尾。

Typical pseudocode for writing is:

OPEN FILE FOR WRITE
WRITE “Hello” TO FILE
CLOSE FILE

Writing data is non-volatile storage: once saved to disk, the data remains even after the program ends or the computer is turned off.

写入数据属于非易失性存储:数据一旦保存到磁盘,即使程序结束或计算机关机,数据仍然保留。

When appending, the old data is not destroyed. This is useful for log files or records that grow over time, such as a school database of student test scores.

追加时旧数据不会被销毁。这对于日志文件或逐渐增长的记录非常有用,例如学校的学生考试成绩数据库。


7. CSV Files and Delimiters | CSV 文件与分隔符

A CSV (Comma Separated Values) file is a common text-file format that stores tabular data. Each line is a record, and each field in the record is separated by a comma. CSV files can be opened by spreadsheets and databases.

CSV(逗号分隔值)文件是一种常见的文本文件格式,用于存储表格数据。每一行是一条记录,记录中的每个字段用逗号分隔。CSV 文件可以被电子表格和数据库打开。

For example, a CSV file storing students’ scores might look like:

Alice,85,Maths
Bob,72,Science
Carol,91,Computing

The comma is called a delimiter. A delimiter is a character used to separate fields. Other common delimiters include the space, the tab, and the semicolon.

逗号被称为分隔符。分隔符是用来分隔字段的字符。其他常见分隔符包括空格、制表符和分号。

When reading a CSV file, each line is split at the commas. Programs can then store each field in a separate variable or array element.

读取 CSV 文件时,每一行都会按逗号拆分。程序随后可以将每个字段存入单独的变量或数组元素中。


8. Errors and Exceptions in File Handling | 文件处理中的错误与异常

Several things can go wrong when using files. If these errors are not handled, the program will crash. Modern programming languages use exceptions to manage errors gracefully.

使用文件时可能出现多种错误。如果这些错误未得到处理,程序就会崩溃。现代编程语言使用异常来妥善管理错误。

  • File not found: attempting to read a file that does not exist. | 文件未找到:试图读取不存在的文件。
  • No permission: the user cannot access the file. | 无权限:用户无法访问文件。
  • Disk full: writing fails because storage is full. | 磁盘已满:存储空间已满导致写入失败。
  • Format error: the data in the file is not in the expected structure. | 格式错误:文件中的数据不符合预期结构。

Exam questions often ask candidates to suggest validation and error-checking when reading a file. A common technique is to check whether a file exists before opening it, and to use try-except structures to catch errors.

考试题常要求考生提出读取文件时的验证和错误检查方法。一种常见技巧是打开文件前先检查文件是否存在,并使用 try-except 结构捕获错误。


9. Fixed-Length and Delimited Records | 定长记录与分隔记录

In structured file storage, there are two main ways to organise records: fixed-length records and variable-length (delimited) records.

在结构化文件存储中,组织记录主要有两种方式:定长记录和变长(分隔)记录。

A fixed-length record reserves the same number of characters for each field. For example, a name might always occupy 20 characters. This makes calculation of positions easy but can waste space.

定长记录为每个字段分配相同数量的字符。例如,姓名始终占用 20 个字符。这种方式便于计算位置,但可能浪费空间。

A delimited record uses a delimiter such as a comma or semicolon to separate fields. This saves space but requires more processing when reading, because the program must scan for the delimiter.

分隔记录使用逗号或分号等分隔符来分隔字段。这种方式节省空间,但读取时需要更多处理,因为程序必须扫描分隔符。

Fixed: 001Alice85Maths002Bob72Science | 定长:001Alice85Maths002Bob72Science
Delimited: 1,Alice,85,Maths / 2,Bob,72,Science | 分隔:1,Alice,85,Maths / 2,Bob,72,Science


10. Key Exam Points | 考点总结

In the IGCSE examination, candidates must be able to interpret pseudocode for file handling and write their own code or pseudocode. The following points are frequently tested.

在 IGCSE 考试中,考生必须能够理解文件处理的伪代码,并且能够编写自己的代码或伪代码。以下要点是高频考点。

  • Know the difference between read, write and append modes. | 掌握读取、写入和追加模式的区别。
  • Always close a file after use. | 使用后务必关闭文件。
  • Use a loop with “WHILE NOT EOF” to read all records. | 使用 “WHILE NOT EOF” 循环读取所有记录。
  • Understand text files and binary files. | 理解文本文件与二进制文件。
  • Be able to explain why files are needed for permanent storage. | 能够解释为什么永久存储需要文件。
  • Recognise that write mode overwrites existing data. | 认识到写入模式会覆盖已有数据。
  • Handle errors using existence checks and exception handling. | 使用存在性检查和异常处理来管理错误。
  • Split delimited records into fields when processing CSV data. | 处理 CSV 数据时,将分隔记录拆分为字段。

By mastering these concepts, learners will be ready to answer both theory questions and practical programming tasks in the examination.

掌握了这些概念,学习者就能够在考试中从容应对理论题和实际编程题。


Published by TutorHao | Computer Science Revision Series | aleveler.com

更多咨询请联系16621398022(同微信)

Comments

屏轩国际教育cambridge primary/secondary checkpoint, cat4, ukiset,ukcat,igcse,alevel,PAT,STEP,MAT, ibdp,ap,ssat,sat,sat2课程辅导,国外大学本科硕士研究生博士课程论文辅导Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from aleveler.com

Subscribe now to keep reading and get access to the full archive.

Continue reading

Exit mobile version