Python TXT, Binary, CSV
Python TXT, Binary, CSV
def text_file_operations(file_name):
while True:
print("\nText File Operations")
print("1. Read File")
print("2. Write to File")
print("3. Append to File")
print("4. Exit")
if choice == "1":
try:
with open(file_name, 'r') as file:
print(file.read())
except FileNotFoundError:
print(f"Sorry, the file {file_name} does not exist.")
else:
print("Invalid choice. Please choose a valid option.")
def binary_file_operations(file_name):
while True:
print("\nBinary File Operations")
print("1. Read File")
print("2. Write to File")
print("3. Append to File")
print("4. Exit")
if choice == "1":
try:
with open(file_name, 'rb') as file:
print(file.read())
except FileNotFoundError:
print(f"Sorry, the file {file_name} does not exist.")
else:
print("Invalid choice. Please choose a valid option.")
- We open the file in binary mode ('rb' for reading, 'wb' for writing, and 'ab' for
appending) using the open function.
- When writing or appending data, we convert the input string to bytes using bytes(data,
'utf-8').
Here's a simple Python program that performs basic operations on a CSV file:
import csv
def csv_file_operations(file_name):
while True:
print("\nCSV File Operations")
print("1. Read File")
print("2. Write to File")
print("3. Append to File")
print("4. Exit")
if choice == "1":
try:
with open(file_name, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
except FileNotFoundError:
print(f"Sorry, the file {file_name} does not exist.")
else:
print("Invalid choice. Please choose a valid option.")
# Call the function with your file name
csv_file_operations('example.csv')
Note: