import csv
import os
import zipfile
def append_csv(file_path, add_info):
# 新增的数据行,以列表的形式表示
# add_info = ["Guo", 150]
csvFile = open(file_path, "a", encoding="UTF-8", newline='')
writer = csv.writer(csvFile)
writer.writerow(add_info)
csvFile.close()
def read_csv_map_0_1(file_path):
# 读取csv至字典
csvFile = open(file_path, "r", encoding="UTF-8")
reader = csv.reader(csvFile)
# 建立空字典
result = {}
for item in reader:
if len(item) > 1:
result[item[0]] = item[1]
csvFile.close()
return result
def read_csv_map_0_2(file_path):
# 读取csv至字典
csvFile = open(file_path, "r", encoding="UTF-8")
reader = csv.reader(csvFile)
# 建立空字典
result = {}
for item in reader:
if len(item) > 2:
result[item[0]] = item[2]
csvFile.close()
return result
def read_csv_map_x_x(file_path, one, two):
# 读取csv至字典
csvFile = open(file_path, "r", encoding="UTF-8")
reader = csv.reader(csvFile)
# 建立空字典
result = {}
for item in reader:
if len(item) > two:
result[item[one]] = item[two]
csvFile.close()
return result
def read_csv_list_0(file_path): # 读取第一列
csvFile = open(file_path, "r", encoding="UTF-8")
reader = csv.reader(csvFile)
result = []
for item in reader:
if len(item) > 0:
if item[0]:
result.append(item[0])
csvFile.close()
return result
def read_csv_list_2(file_path): # 读取第三列
csvFile = open(file_path, "r", encoding="UTF-8")
reader = csv.reader(csvFile)
result = []
for item in reader:
if len(item) > 2:
if item[2]:
result.append(item[2])
csvFile.close()
return result
def read_csv_list_1(file_path): # 读取第二列
csvFile = open(file_path, "r", encoding="UTF-8")
reader = csv.reader(csvFile)
result = []
for item in reader:
if len(item) > 1:
if item[1]:
result.append(item[1])
csvFile.close()
return result
def read_csv_list_one_line_by_first(file_path, key):
csvFile = open(file_path, "r", encoding="UTF-8")
reader = csv.reader(csvFile)
result = []
for item in reader:
if len(item) > 0:
if item[0] == key:
for num in range(1, len(item)):
result.append(item[num])
csvFile.close()
return result
def read_csv_all(file_path):
csvFile = open(file_path, "r", encoding="UTF-8")
reader = csv.reader(csvFile)
result = []
for item in reader:
result.append(item)
return result
def replace_one_line_by_key_0(file_path, line_new):
res = []
csvreadfile = open(file_path, 'r')
reader = csv.reader(csvreadfile)
for line in reader:
res.append(line)
csvreadfile.close()
num = -1
for new in range(len(res)):
one_line_old = res[new]
print(one_line_old[0] + "||" + line_new[0])
if one_line_old[0] == line_new[0]:
print(new)
num = new
if num != -1:
res[num] = line_new
csvfile = open(file_path, 'w')
writer = csv.writer(csvfile)
writer.writerows(res)
csvfile.close()
Python3 CSV操作
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 001.设立明确的目标 “我要减肥”只不过是一个模棱两可的要求,而“我今年10月份前要减掉5公斤”则是定义了时间和...
- 问题描述: 1.商家无法兑现承诺准时上门。 按照提前预约的时间8:00在家等,等了一个小时没来,8:10微信联系不...