πŸ“

File Handling Techniques in Python

Aug 22, 2024

Notes on File Handling in Python

Overview

  • Continuation of previous discussion on file handling in Python.
  • Focus on additional methods: readlines() and writelines().

Key Points

Readlines Method

  • Purpose: Used to read lines from a file one by one.
  • Implementation:
    • Create a file called myfile.txt.
    • Write a line in it (e.g., "Harry bhai python course is great").
    • Use f = open('myfile.txt') to open the file and read lines.
    • Example of reading lines: for line in f: print(line)
    • If there are no more lines, the output will be an empty string.

Data Example

  • Example of reading multiple lines:
    • Input: 56, 45, 67 12, 34, 63 13, 64, 23
    • Split each line using line.split(',') to extract individual marks.
    • Use loop counter i to keep track of student numbers.

Typecasting

  • Conversions: Convert strings to integers for calculations.
    • Example: int(value) * 2 for calculating percentages.*

Writelines Method

  • Purpose: To write a sequence of strings to a file.
  • Implementation:
    • Create or open a file, e.g., myfile2.txt.
    • Use f.writelines(lines) to write lines to the file.
    • Note: writelines() does not add newline characters automatically; you must handle that manually.

Example of Writing Lines

  • Writing lines without a new line character: lines = ['line 1', 'line 2', 'line 3'] f.writelines(lines) # No automatic new line

Course Feedback

  • Encouragement for viewers to review the course and provide feedback for future students.
  • Importance of sharing experiences and ratings to help newcomers.

Conclusion

  • Summary of file handling methods discussed.
  • Importance of mastering file read/write operations in Python.