In Python, you can open a file using the built-in open() function. This function allows you to read, write, or append data to a file.
Syntax of open() function:
file = open('filename', 'mode')
filename: The name of the file you want to open (including its path if it's not in the same directory as the script).
mode: The mode in which to open the file. It can be:
'r': Read (default mode). Opens the file for reading.
'w': Write. Opens the file for writing (creates the file if it doesn't exist, or truncates it to zero length if it does).
'a': Append. Opens the file for appending (creates the file if it doesn't exist).
'b': Binary. Can be used with other modes for binary files.
'x': Exclusive creation. Creates a new file, and returns an error if the file exists.
't': Text (default mode). Used for text files.
Examples of opening files:
1. Opening a File for Reading ('r' Mode):
This is the default mode. If the file doesn’t exist, it raises an error (FileNotFoundError).
file = open('example.txt', 'r')
content = file.read() # Reads the entire file content
print(content)
file.close() # Don't forget to close the file
2. Opening a File for Writing ('w' Mode):
If the file already exists, it will overwrite the content. If it doesn't exist, a new file will be created.
file = open('example.txt', 'w')
file.write("This is a new file.\n")
file.write("Hello, Python!")
file.close()
3. Opening a File for Appending ('a' Mode):
If the file already exists, it will not overwrite the content; instead, it will add the new data at the end of the file.
file = open('example.txt', 'a')
file.write("\nAppending this new line.")
file.close()
4. Opening a File in Binary Mode ('b' Mode):
This is used for non-text files like images or audio files.
file = open('example.jpg', 'rb') # Open image in binary mode
content = file.read()
file.close()
Using with Statement to Open a File (Recommended Approach):
The with statement is a context manager that automatically handles opening and closing the file. This is a cleaner and more efficient way to work with files.
with open('example.txt', 'r') as file:
content = file.read() # Read the entire file content
print(content)
The file is automatically closed once the block of code is exited, even if an error occurs.
Modes Summary:
Reading Files:
read(): Reads the entire content of the file.
readline(): Reads one line at a time.
readlines(): Reads all lines and returns them as a list.
Example:
with open('example.txt', 'r') as file:
content = file.readlines() # Read all lines into a list
for line in content:
print(line.strip()) # Strip newline characters
Writing to Files:
write(): Writes a string to the file. If the file is opened in 'w' or 'a' mode, it will overwrite or append to the file.
writelines(): Writes a list of strings to the file.
Example:
lines = ["Hello, world!\n", "Python is awesome.\n"]
with open('example.txt', 'w') as file:
file.writelines(lines)
Let me know if you need further explanations or additional examples!
0 Comments