Python Tutorial
Python Variable
Python Operators
Python Sequence
Python String
Python Flow Control
Python Functions
Python Class and Object
Python Class Members (properties and methods)
Python Exception Handling
Python Modules
Python File Operations (I/O)
In Python, you can perform various file operations such as reading, writing, and appending data to files. Here is an overview of the basic operations for working with files in Python:
To open a file, use the open()
function. It takes two arguments: the file path and the mode in which you want to open the file. The mode can be 'r' for reading, 'w' for writing, 'a' for appending, and 'x' for creating a new file. If the mode is not specified, it defaults to 'r' (reading).
file = open("example.txt", "r")
After you have finished working with a file, it is important to close it using the close()
method. This releases the resources associated with the file and prevents potential issues with file handling.
file.close()
To read the entire content of a file, use the read()
method.
file = open("example.txt", "r") content = file.read() print(content) file.close()
To read a file line by line, you can use a for
loop:
file = open("example.txt", "r") for line in file: print(line.strip()) file.close()
To write data to a file, open it in 'w' (write) mode and use the write()
method. Note that this will overwrite the file if it already exists.
file = open("output.txt", "w") file.write("Hello, world!") file.close()
To append data to an existing file, open it in 'a' (append) mode and use the write()
method.
file = open("output.txt", "a") file.write("\nAppending this line.") file.close()
with
statement (recommended):To simplify file handling and ensure that the file is properly closed, you can use the with
statement, which automatically closes the file after the indented block of code is executed.
with open("example.txt", "r") as file: content = file.read() print(content)
In this example, there is no need to call file.close()
, as it is automatically closed by the with
statement.
These are the basic operations for working with files in Python. By opening files in different modes, you can read, write, and append data as needed, while always remembering to close the file after use. The with
statement is the recommended way to handle files, as it ensures proper resource management.
How to open and read files in Python:
open
function to open a file and the read
method to read its content.file_path = "example.txt" with open(file_path, "r") as file: content = file.read() print(content)
Writing to files in Python:
file_path = "example.txt" with open(file_path, "w") as file: file.write("Hello, World!")
Appending data to files in Python:
file_path = "example.txt" with open(file_path, "a") as file: file.write("\nAppended content.")
Closing files in Python:
file_path = "example.txt" file = open(file_path, "r") content = file.read() file.close()
Working with text files in Python:
file_path = "text_file.txt" with open(file_path, "r") as file: content = file.read() print(content)
Binary file operations in Python:
image_path = "image.png" with open(image_path, "rb") as file: binary_data = file.read()
Handling file exceptions in Python:
FileNotFoundError
or PermissionError
when working with files.try: with open("nonexistent_file.txt", "r") as file: content = file.read() except FileNotFoundError: print("File not found.")
File modes in Python (r, w, a, etc.):
# Read mode with open("example.txt", "r") as file: content = file.read() # Write mode with open("example.txt", "w") as file: file.write("Hello, World!") # Append mode with open("example.txt", "a") as file: file.write("\nAppended content.")
Using with statement for file handling in Python:
with
statement ensures that the file is properly closed, even if an exception occurs.with open("example.txt", "r") as file: content = file.read()
Seek and tell operations on files in Python:
seek
to move the file cursor, and tell
to get the current position in the file.with open("example.txt", "r") as file: file.seek(5) # Move to the 6th character content = file.read(10) # Read the next 10 characters position = file.tell() # Get the current position
Copying and moving files in Python:
shutil
module for file operations like copying (shutil.copy
) and moving (shutil.move
).import shutil source_file = "example.txt" destination_path = "backup/example.txt" shutil.copy(source_file, destination_path)
File compression and decompression in Python:
gzip
or zipfile
to compress and decompress files.import gzip with open("example.txt", "rb") as file: with gzip.open("example.txt.gz", "wb") as compressed_file: compressed_file.write(file.read())
Working with CSV and JSON files in Python:
csv
module for CSV files and the json
module for JSON files.import csv import json # Reading CSV with open("data.csv", "r") as csv_file: csv_reader = csv.reader(csv_file) for row in csv_reader: print(row) # Writing JSON data = {"name": "John", "age": 30, "city": "New York"} with open("data.json", "w") as json_file: json.dump(data, json_file)