csv

使用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 函数接受一个文件路径和一个列索引,然后检查该列是否有任何数据。你可以根据实际情况调整列索引。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 说明 读取一个CSV 文件 例子 最全的 一个简化版本 参数 filepath_or_buffer : str,p...
    喵_十八阅读 2,974评论 0 0
  • pandas.read_csv参数整理 读取CSV(逗号分割)文件到DataFrame 也支持文件的部分导入和选择...
    逍遥_yjz阅读 1,406评论 0 2
  • 读取CSV(逗号分割)文件到DataFrame 也支持文件的部分导入和选择迭代 更多帮助参见:http://pan...
    原点_da4e阅读 603评论 0 0
  • Pandas使用一个二维的数据结构DataFrame来表示表格式的数据,相比较于Numpy,Pandas可以存储混...
    nowkeepgoing阅读 873评论 0 0
  • 以下文章来源于大数据DT ,作者李庆辉导读:pandas.read_csv接口用于读取CSV格式的数据文件,由于C...
    春秋不做梦阅读 4,026评论 0 1