Files
Introduction to File Handling in Python
Overview of file handling concepts in Python
Importance of reading and writing to files outside the Python environment
Types of Files
Example of plain text file with English text
Can be opened using TextEdit (macOS) or Notepad (Windows)
Contains unformatted text
Opening Files
Use the
open()function to open a fileSyntax:
open("filename.txt", "mode")filename: name of the filemode: indicates the operation type
Common modes:
"r": open for reading (default mode)"w": open for writing (truncate existing content)"a": open for appending (write at the end of the file)
Reading Files
Store the return value of
open()in a variable (e.g.,file)The
read()method:Use
file.read(n)to read the nextncharactersUse
file.read()without arguments to read the entire file
Empty string returned when end of file is reached
Remember to close the file using
file.close()
Reading Lines
Use
readline()to read one line at a time:Each call to
file.readline()retrieves the next lineEach line ends with a newline character (
\n)
Strip newline characters using
strip()method
Writing Files
To create a new file or overwrite an existing one, use
open("newfile.txt", "w")Writing text using
file.write("text")NN: If needing new lines, include
\nwithin the write stringAlways close the file after writing with
file.close()
Modes of Writing
Opening a file in
"w"mode truncates existing contentTo append content without deleting existing data, use
"a"modeNew content is added to the end of the file
Example Demonstration
Create a file called
hello.txtWrite "hello
" followed by "world
"
Check file contents to see proper line placement
Conclusion
Recap of file operations: opening, reading, writing, and appending
Highlight the importance of closing files in programming