Python File Handling
To open and handle files in Python, you can follow the steps below:
- Open a File
Use the
open()
function, specifying the filename and mode:file = open('filename', 'mode')
- Specify the Mode
Choose a mode, such as ‘r’ for reading or ‘w’ for writing.
- Reading or Writing to the File
To read or write, use:
content = file.read()
file.write('Hello, world!')
- Close the File
Don’t forget to close the file when done:
file.close()
Here is an example of file handling in Python:
# Writing to a file
with open('hello.txt', 'w') as f:
f.write('Hello, world!')
# Reading from a file
with open('hello.txt', 'r') as f:
content = f.read()
print(content)