使用Python原生函數(shù)(即不依賴第三方庫)實(shí)現(xiàn)CSV的增刪改查可以通過基本的文件讀寫和數(shù)據(jù)處理操作來完成。下面是一個(gè)簡單的例子,用于演示如何實(shí)現(xiàn)這些功能:
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)
如果你想查詢某列是否有數(shù)據(jù),你可以修改 search_records 函數(shù)以只返回指定列的數(shù)據(jù)。下面是一個(gè)例子:
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}")
在這個(gè)例子中,column_has_data 函數(shù)接受一個(gè)文件路徑和一個(gè)列索引,然后檢查該列是否有任何數(shù)據(jù)。你可以根據(jù)實(shí)際情況調(diào)整列索引。