File I/O is the process of reading and writing data to and from files on disk. In Python, you can use the built-in open
function to open a file and access its contents.
Here's an example of how to read the contents of a file:
pythonwith open("filename.txt", "r") as file:
contents = file.read()
print(contents)
In this example, we use the with
statement to open the file in read mode ("r"
) and assign it to the variable file
. The with
statement automatically closes the file when we're done with it. We then use the read
method of the file object to read the entire contents of the file into the variable contents
.
Here's an example of how to write data to a file:
pythonwith open("filename.txt", "w") as file:
file.write("Hello, world!")
In this example, we open the file in write mode ("w"
) and assign it to the variable file
. We then use the write
method of the file object to write the string "Hello, world!" to the file.
Exception Handling
Exception handling is the process of handling errors and exceptions in your code. In Python, you can use the try
and except
statements to catch and handle exceptions.
Here's an example of how to catch an exception:
pythontry:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
In this example, we use the try
statement to attempt to divide the number 1 by 0, which would normally result in a ZeroDivisionError
. We use the except
statement to catch the exception and print an error message.
You can also use the finally
statement to execute some code after the try
and except
statements, regardless of whether an exception was raised or not:
pythontry:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("This will always be executed.")
In this example, the finally
statement is used to print a message after the try
and except
statements have executed, regardless of whether an exception was raised or not.
0 Comments