Python - Files I/O
In Python, you can perform input/output (I/O) operations on files using the built-in functions and methods provided by the language. The main functions to work with files are open(), close(), read(), write(), and seek().
Here is a brief explanation of these functions:
open(): This function is used to open a file and return a file object. It takes two arguments: the name of the file you want to open and the mode in which you want to open it (read, write, append, etc.).
- close(): This method is used to close the file object and release any system resources associated with it.
- read(): This method is used to read data from a file. It takes an optional argument that specifies the number of bytes to read. If no argument is provided, it will read the entire file.
- write(): This method is used to write data to a file. It takes a string as an argument that represents the data to be written.
- seek(): This method is used to move the file pointer to a specified position in the file. It takes an integer argument that represents the offset from the beginning of the file.
Python also provides different modes to open a file. Some of the most commonly used modes are:
- 'r': open for reading (default)
- 'w': open for writing, truncating the file first
- 'a': open for writing, appending to the end of the file if it exists
- 'x': open for exclusive creation, failing if the file already exists
- 'b': binary mode (e.g. 'rb' for reading a binary file)
Here are some examples of file I/O operations in Python:
Writing to a file:
# Open file for writing
file = open("example.txt", "w")
# Write to file
file.write("Hello, World!")
# Close file
file.close()
Reading from a file:
# Open file for reading
file = open("example.txt", "r")
# Read entire file contents
contents = file.read()
# Print contents to console
print(contents)
# Close file
file.close()
Appending to a file:
# Open file for appending
file = open("example.txt", "a")
# Append to file
file.write("\nThis is a new line.")
# Close file
file.close()
Reading a file line-by-line:
# Open file for reading
file = open("example.txt", "r")
# Read file line-by-line
for line in file:
print(line)
# Close file
file.close()
Using with statement to automatically close the file:
# Open file using with statement
with open("example.txt", "r") as file:
# Read entire file contents
contents = file.read()
# Print contents to console
print(contents)