CMPE 30032 Module 2 File Handling in Python PDF
Document Details
Uploaded by CalmFuchsia
Polytechnic University of the Philippines
Tags
Related
- COMP1210 Lecture Notes 4 on File Processing PDF
- Lesson 10_ Read and Write Files - Check Your Understanding_ Su24_ MSBC 5070-601-602 In-Person_ Survey of Business Analytics.pdf
- All MCQS for Exam.pdf
- UNIT -III_Python file handling, reading and writing files.pdf
- Unit 2 Database Backup and CSV File Handling.pdf
- Lecture5_File_Handling_Python.pptx
Summary
This document is a module covering file handling in Python. It includes explanations of text and binary files, file operations (opening, reading, writing, appending, and closing), and file permissions. A variety of code examples are provided.
Full Transcript
CMPE 30032 Module 2 File Handling in Python Be able to read, comprehend, trace, adapt and create Python code that: Opens a file Learning Reads data from a file into a Goals/Objectives...
CMPE 30032 Module 2 File Handling in Python Be able to read, comprehend, trace, adapt and create Python code that: Opens a file Learning Reads data from a file into a Goals/Objectives program Writes data from a program into a file Appends data from a program into a file Closes a file What Is File? File is a named location on disk to store related information. It is used to permanently store data in a non-volatile memory (e.g., hard disk). Since Random Access Memory (RAM) is volatile which loses its data when computer is turned off, we use files for future use of the data. When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed, so that resources that are tied with the file are freed. Hence, in Python, a file operation takes place in the following order. 1. Open a file 2. Read or write (perform operation) 3. Close the file File Types? In Python, there are two types of files. They are: ❑ Text files ❑ Binary files Text files store the data in the form of characters. For example, if we store employee name “Jerald”, it will be stored as 6 characters and the employee salary 8900.75 is stored as 7 characters. Text files are used to store characters or strings. File Types? Binary files store entire data in the form of bytes, i.e., a group of 8 bits each. For example, a character is stored as a byte and an integer is stored in the form of 8 bytes (on a 64-bit machine). When the data is retrieved from the binary file, the programmer can retrieve the data as bytes. Binary files can be used to store text, images, audio and video. Image files are generally available in.jpg,.gif or.png formats. We cannot use text files to store images as the images do not contain characters. What Is File Handling? Computer programs can import data from and export data to files outside the code. Read - Get data Your code External file from a file into your program Write/Append - send data from your program into a file File Permissions Read - File can be ‘looked at’ by the program r but not changed. Error if the file doesn’t already exist. Append - File can be added to. File is created if a it doesn’t already exist. Write - Overwrites existing data, starting from w the beginning of the file. File is created if it doesn’t already exist. Read From a File Read From A File - The Algorithm 1. Connect to and open the file a. Give the file name and path b. Set the permissions for opening 2. Read the contents into a variable 3. Output the variable 4. Close the file. 4. ‘r’ means read Read All From A File - How To Code only. The program can look at data from 1. Create a new variable 2. ‘open’ tells the the file but not change to store the contents of program to open the it. the file. file. myFile = open("test.txt", "r") for line in myFile: print(line) 3. Put the +whole myFile.close() filename https://docs.python.org/3/library/functions.html#open Read From A File - How To Code 5. ‘for’ is another type of 6. ‘line in myFile’ sets the loop. It has a fixed length length of the loop to the so does not need a number of lines in the condition. external file. myFile = open("test.txt", "r") for line in myFile: 7. Outputs each line from print(line) the file one by one. The loop moves through each myFile.close() one. 8. ALWAYS close the file once you have finished with it. Read Functions read(n) – Read at most n characters form the file. Reads till end of file if it is negative or None. For example: f = open(“text.txt”) print (f.read()) # Reads the entire file f.close() f = open(“text.txt”) print(f.read(5)) # Reads the first 5 characters of the file f.close() readline() – Read and return one line from the file. Reads in at most n bytes if specified. For example: f = open(“text.txt) print(f.readline())#Reads the first line of the file f.close() Read Functions readlines() – Read and return a list of lines from the file. Reads in at most n bytes/characters if specified. For example: f = open(“text.txt”) data = f.readlines() for line in data: print(line) Write & Append to a File 4. ‘w’ means write. If Write To A File - How To Code there’s an existing file 1. Create a new variable 2. ‘open’ tells the with this name Python to store the contents of program to open the will open it. If not it the file. file. will create it. myFile = open("test.txt", "w") myFile.write(“Andy”) 3. Put the whole filename myFile.close() 5. Put the data or variable to be written Append To A File - How To Code 4. ‘a’ means append. 1. Create a new variable 2. ‘open’ tells the This means ‘add to to store the contents of program to open the the end’ of the file. the file. file. myFile = open("test.txt", "a") myFile.write(“Andy”) 3. Put the whole filename myFile.close() 5. Put the data or variable to be written Lab Exercise 4 (Today) ( 50 points). Write a python program that reads a text file named numbers.txt that contains 20 positive integers. The program will create two other text file; the first text file will be named even.txt that will contain all even numbers extracted from the number.txt the second text file will be named odd.txt that will contain all odd numbers extracted from the number.txt. Lab Exercise 5 (Deadline : April 30,2024) 5.1 (25 points). Write a method in python to write multiple line of text contents into a text file mylife.txt. See output: Enter line: Beautiful is better than ugly. Are there more lines y/n? y Enter line: Explicit is better than implicit. Are there more lines y/n? y Enter line: Simple is better than complex. Are there more lines y/n? n Lab Exercise 5 (Deadline : April 30,2024) 5.2 (50 points). Write a method in python will create two separate text files after reading the source text file named integers.txt that contains 20 integers. The first output file will be named double.txt containing the square of all even integers found in integers.txt and the second file will be named triple.txt containing the cube of all odd numbers found in the integers.txt. Lab Exercise 5 (Deadline : April 30,2024) 5.3 (50 points). Write a Python program that read a binary file containing the name of 20 students together with their General Weighted Average (GWA). The program will output the name of the student who got the highest GWA (including the GWA).