Reading from and Writing to Files
- Definition: File I/O (Input/Output) operations allow you to read from and write to files.
- Opening a File: Use the
open()function to open a file. The mode specifies whether you want to read ('r'), write ('w'), or append ('a') to the file. pythonfile = open("example.txt", "r") # Open for reading file = open("example.txt", "w") # Open for writing file = open("example.txt", "a") # Open for appending - Reading from a File: Use methods like
read(),readline(), orreadlines()to read the content. pythonfile = open("example.txt", "r") content = file.read() print(content) file.close() - Writing to a File: Use the
write()method to write content to a file. pythonfile = open("example.txt", "w") file.write("Hello, World!") file.close() - Using
withStatement: Thewithstatement ensures that the file is properly closed after its suite finishes. pythonwith open("example.txt", "r") as file: content = file.read() print(content)
Working with File Paths
- Definition: File paths specify the location of a file in the file system.
- Absolute vs. Relative Paths:
- Absolute Path: Specifies the complete path from the root directory. python
file = open("/home/user/example.txt", "r") - Relative Path: Specifies the path relative to the current working directory. python
file = open("example.txt", "r")
- Absolute Path: Specifies the complete path from the root directory. python
- Using
osandpathlibModules: These modules provide functions to work with file paths. pythonimport os print(os.path.abspath("example.txt")) # Output: /home/user/example.txt from pathlib import Path print(Path("example.txt").resolve()) # Output: /home/user/example.txt