โ Python File Handling
๐๐ File handling allows Python programs to read and write data from files.
๐ Very important in data science because most datasets come as:
โ CSV files
โ Text files
โ Logs
โ JSON files
๐น 1. Opening a File
Python uses the open() function.
Syntax:
open("filename", "mode")Example:
file = open("data.txt", "r")๐ "r" โ Read mode
๐น 2. File Modes
- "r" โ Read file
- "w" โ Write file (overwrites existing content)
- "a" โ Append file (adds to existing content)
- "r+" โ Read and write
๐น 3. Reading a File
- Read Entire File:
file.read()- Read One Line:
file.readline()- Read All Lines:
file.readlines()๐น 4. Writing to a File
file = open("data.txt", "w")
file.write("Hello Data Science")
file.close()
โ "w" will overwrite existing content.
๐น 5. Append to File
file = open("data.txt", "a")
file.write("\nNew line added")
file.close()
โ Adds content without deleting old data.
๐น 6. Best Practice (Very Important โญ)
Use with statement.
with open("data.txt", "r") as file:
content = file.read()
print(content)
โ Automatically closes the file.
๐น 7. Why File Handling is Important?
Used for:
โ Reading datasets
โ Saving results
โ Logging machine learning models
โ Data preprocessing
๐ฏ Todayโs Goal
โ Understand file modes
โ Read files
โ Write files
โ Use with open()
๐ File handling is used heavily when working with CSV datasets in data science.
Double Tap โฅ๏ธ For More