TGViewer
Data Science & Machine Learning Data Science & Machine Learning @datasciencefun ยท 77.8K subscribers
Post #4091 4.21K
Data Science Roadmap

โœ… 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
  • โค 13
More from @datasciencefun
  1. Oct 15, 2026Post #4665
  2. Oct 15, 2026Post #4664
  3. Oct 15, 2026Post #4663
  4. Oct 15, 2026Post #4662
  5. Oct 13, 2026๐—ง๐—ข๐—ฃ ๐—™๐—ฅ๐—˜๐—˜ ๐—–๐—ข๐—จ๐—ฅ๐—ฆ๐—˜๐—ฆ ๐—ง๐—ข ๐—•๐—ข๐—ข๐—ฆ๐—ง ๐—ฌ๐—ข๐—จ๐—ฅ ๐—ฆ๐—ž๐—œ๐—Ÿ๐—Ÿ๐—ฆ ๐—œ๐—ก ๐Ÿฎ๐Ÿฌ๐Ÿฎ๐Ÿฒ! Explorโ€ฆ
  6. Oct 12, 2026Used when you want to perform calculations for each department. Simple rule: DISTINCT โ†’ Giโ€ฆ
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook โ†’Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 โ†’