使用Python原生函数(即不依赖第三方库)实现CSV的增删改查可以通过基本的文件读写和数据处理操作来完成。下面是一个简单的例子,用于演示如何实现这些功能:
import csv
import os
def read_csv(file_path):
data = []
if os.path.exists(file_path):
with open(file_path, 'r', newline='') as csvfile:
csv_reader = csv.reader(csvfile)
data = [row for row in csv_reader]
return data
def write_csv(file_path, data):
with open(file_path, 'w', newline='') as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerows(data)
def add_record(file_path, new_record):
data = read_csv(file_path)
data.append(new_record)
write_csv(file_path, data)
def delete_record(file_path, index):
data = read_csv(file_path)
if 0 <= index < len(data):
del data[index]
write_csv(file_path, data)
else:
print("Index out of range.")
def update_record(file_path, index, updated_record):
data = read_csv(file_path)
if 0 <= index < len(data):
data[index] = updated_record
write_csv(file_path, data)
else:
print("Index out of range.")
def search_records(file_path, search_term):
data = read_csv(file_path)
search_result = [record for record in data if any(search_term.lower() in field.lower() for field in record)]
return search_result
# Example Usage:
file_path = 'example.csv'
# Add a record
new_record = ['John Doe', '30', 'john.doe@email.com']
add_record(file_path, new_record)
# Update a record
update_index = 0
updated_record = ['Jane Doe', '25', 'jane.doe@email.com']
update_record(file_path, update_index, updated_record)
# Delete a record
delete_index = 1
delete_record(file_path, delete_index)
# Search for records
search_term = 'Doe'
search_result = search_records(file_path, search_term)
print("Search Result:", search_result)
# Read all records
all_records = read_csv(file_path)
print("All Records:", all_records)
如果你想查询某列是否有数据,你可以修改 search_records
函数以只返回指定列的数据。下面是一个例子:
import csv
import os
def read_csv(file_path):
data = []
if os.path.exists(file_path):
with open(file_path, 'r', newline='') as csvfile:
csv_reader = csv.reader(csvfile)
data = [row for row in csv_reader]
return data
def column_has_data(file_path, column_index):
data = read_csv(file_path)
# Check if column_index is valid
if not (0 <= column_index < len(data[0])):
print("Invalid column index.")
return False
# Check if any row in the specified column has data
return any(row[column_index] for row in data)
# Example Usage:
file_path = 'example.csv'
column_index_to_check = 1 # Change this to the index of the column you want to check
has_data = column_has_data(file_path, column_index_to_check)
print(f"Column {column_index_to_check} has data: {has_data}")
在这个例子中,column_has_data
函数接受一个文件路径和一个列索引,然后检查该列是否有任何数据。你可以根据实际情况调整列索引。