csv文件处理

    xiaoxiao2025-04-03  11

    csv文件格式的处理 读取整个csv文件

    # 读取整个csv filename = 'sitka_weather_07-2014.csv' with open(filename) as f: read = f.read() print(read)

    分析csv头文件

    # 分析csv头文件 import csv filename = 'sitka_weather_07-2014.csv' with open(filename) as f: read = csv.reader(f) header_row = next(read) # next迭代器 print(header_row) # 打印文件头极其位置 import csv filename = 'sitka_weather_07-2014.csv' with open(filename) as f: read = csv.reader(f) header_row = next(read) for index, column_header in enumerate(header_row): print(index, column_header) # 将头文件处理成字典形式 import csv filename = 'sitka_weather_07-2014.csv' file_header = {} # enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标 with open(filename) as f: read = csv.reader(f)# reader 为阅读器 header_row = next(read) for index, column_header in enumerate(header_row): file_header[index + 1] = column_header # 索引 + 1 print(file_header)

    对csv文件的行操作和列操作

    # 提取并读取数据(行操作) import csv filename = 'sitka_weather_07-2014.csv' with open(filename) as f: read = csv.reader(f) header_row = next(read) highs = [] for line in read: highs.append(line) print(highs[2]) # 列表索引 提取第三行 print(highs[0:3]) # 切片 # 提取并读取数据(列操作) import csv filename = 'sitka_weather_07-2014.csv' with open(filename) as f: read = csv.reader(f) header_row = next(read) highs = [] for line in read: highs.append(line[2]) # 索引,读取每一行中第三个元素加到列表中 print(highs)

    对csv进行字典操作

    # 使用DictReader 返回的每一个单元格都放在一个字典的值内,而这个字典的键则是这个单元格的标题 # 逐行读取 & 读取某一行 import csv filename = 'sitka_weather_07-2014.csv' with open(filename) as f: read = csv.DictReader(f) rows = [row for row in read] print(rows) print(rows[1]) # 此处为行索引 # 根据条件提取某一行 import csv filename = 'sitka_weather_07-2014.csv' with open(filename) as f: read = csv.DictReader(f) for row in read: if row['Max TemperatureF'] == '64': print(row) # 读取某一列 import csv filename = 'sitka_weather_07-2014.csv' with open(filename) as f: read = csv.DictReader(f) column = [row['Max TemperatureF'] for row in read] print(column)
    最新回复(0)