csv

使用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)整列索引。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 說明 讀取一個(gè)CSV 文件 例子 最全的 一個(gè)簡化版本 參數(shù) filepath_or_buffer : str,p...
    喵_十八閱讀 3,094評論 0 0
  • pandas.read_csv參數(shù)整理 讀取CSV(逗號分割)文件到DataFrame 也支持文件的部分導(dǎo)入和選擇...
    逍遙_yjz閱讀 1,615評論 0 2
  • 讀取CSV(逗號分割)文件到DataFrame 也支持文件的部分導(dǎo)入和選擇迭代 更多幫助參見:http://pan...
    原點(diǎn)_da4e閱讀 624評論 0 0
  • Pandas使用一個(gè)二維的數(shù)據(jù)結(jié)構(gòu)DataFrame來表示表格式的數(shù)據(jù),相比較于Numpy,Pandas可以存儲混...
    nowkeepgoing閱讀 908評論 0 0
  • 以下文章來源于大數(shù)據(jù)DT ,作者李慶輝導(dǎo)讀:pandas.read_csv接口用于讀取CSV格式的數(shù)據(jù)文件,由于C...
    春秋不做夢閱讀 4,495評論 0 1

友情鏈接更多精彩內(nèi)容