VJC Chapter 6 File IO
Uploaded by cheesemuffin · 10 December 2025
Preview
VJC/H2Computing/9569 Chapter 6: File Input/Output (I/O) Contents 1. Introduction 2 2. Open and Close Files 2 2.1 Opening a non-existent file 3 2.2 Using the with method 3 3. Read from a file 3 3.1 Example: read() 4 3.2 Example: readline() 5 3.3 Example: readlines() 6 4. Writing and Appending to a File 6 4.1 Example: write() 6 4.2 Example: writelines() 7 5. Text File & Binary File 8 6. CSV File I/O 8 6.1 Python CSV Module 9 6.2 Example: csv.reader() 9 6.3 Example: Save result as a list 9 6.4 Example: Save header and data as two separate lists 11 6.5 Using csv.writer() 11 6.6 Example: writerow() and writerows() 11 7. JSON Processing 12 7.1 Example: dumps() 13 7.2 Example: More readable version 13 8. Types of files 14 8.1 Serial Files 14 8.2 Sequential Files 14 9. File Paths 14 9.1 Absolute Path 14 9.2 Relative Path 15 Referenced Readings 17
VJC/H2Computing/9569 Syllabus Learning Outcomes 2.3 Implementing Algorithms and Data Structures 2.3.4 Store data in and retrieve data from serial and sequential text files. 1. Introduction File is a named location on a disk to store related information. ● It uses non-volatile memory, e.g. hard disk, to store data permanently. ● A file can be in text or binary format. Advantages of using a file: ● It is more efficient to read large amounts of data from a file, compared to manual data entry. ● We are able to output the results to a file for ease of future reference. A file operation takes place in the following order: ● Open a file ● Perform operations ● Close the file 2. Open and Close Files Python has a built-in function open(file_path) to open a file. ● The open() function returns a file object, also called a file handler, as it is used to read or modify the file accordingly. To read data from a file object, use its read() method. To close a file object, use its close() method. It flushes any unwritten information and closes the file object, after which no more writing can be done. This prevents accidental access to an open file. Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file to release the resources.
VJC/H2Computing/9569 2.1 Opening a non-existent file It is important to ensure the file resides in the same folder as your Python notebook or file. Assuming test.txt is not in the same folder as the Python file, you will get similar error messages. 2.2 Using the with method Another way of opening a file is using the with method. This meth
Content continues in the PDF.
Related notes
- VJC Chapter 21 SQLite with PythonNotes/Practices · 2025
- VJC Chapter 23 Web Applications PrinciplesNotes/Practices · 2025
- VJC Chapter 10 RecursionNotes/Practices · 2025
- VJC Chapter 20 SQLNotes/Practices · 2025
- VJC Chapter 16 Hash TableNotes/Practices · 2025
- VJC Chapter 22 NoSQLNotes/Practices · 2025

