samuel bajracharya
8 pages
samuel bajracharya
8 pages
220
/ 8
File Handling and Data Processing in Python
Contents
1 Introduction 3
2 Opening a File 3
3 Reading a Text File 3
3.1 Why use with? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
4 Reading Line by Line 4
4.1 Why line by line? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
5 EOF Concept 4
6 Passwords and Hash Concept 4
7 Stripping Data 4
8 File as Database (Simple Idea) 5
9 Guess Game Record System 5
9.1 Why store score in file? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
10 Updating File Data 5
11 Append Mode 5
12 CSV Files 6
13 Reading CSV File 6
14 next() Function 6
15 Processing CSV Rows 6
16 Calculating Percentage 6
17 Why File Handling is Important 6
18 Bitwise Operators (Introduction) 7
1
19 AND Operator (&) 7
20 OR Operator (—) 7
21 Right Shift ( ) 7
22 Bitwise Trick: Even or Odd 8
23 Rule 8
24 Real-world Use of Bitwise 8
25 Final Summary 8
2
1 Introduction
Till now, we worked with:
Variables
Conditions
Loops
Functions
Modules
Now we move to something very powerful:
File Handling
File handling allows Python programs to:
Store data permanently
Read external data
Process large datasets
This is how real applications work.
2 Opening a File
Basic syntax:
open (" filename ", " mode ")
Modes:
”r” read
”w” write
”a” append
3 Reading a Text File
with open (" mytext . txt " , " r ") as file :
content = file . read ()
print ( content )
3.1 Why use with?
with automatically closes the file.
Without with, file must be closed manually.
3
/ 8
End of Document
220