需求:將a.csv中,相同手機號,只要有乙個傳送成功,則其餘改為傳送成功
# 遍歷軟體執行的資料夾
path_dir = os.getcwd()
for root, dirs, files in os.walk(path_dir):
for file in files:
if file.endswith('.csv'):
f = open(file, encoding='gbk')
reader1 = csv.reader(f)
# **列
tel_col = [column[2] for column in reader1]
tel_li = tel_col[1:]
# print(tel_li)
f.close()
# 錯誤描述列
f = open(file, encoding='gbk')
reader2 = csv.reader(f)
result_col = [column[6] for column in reader2]
result_li = result_col[1:]
# print(result_li)
f.close()
# 拿到**號碼,及其對應的索引列表
tel = defaultdict(list)
tel_dic = {}
for k, va in [(v, i) for i, v in enumerate(tel_li)]:
tel_dic = dict(tel)
# print(tel_dic)
# res = defaultdict(list)
# res_dic = {}
# for k, va in [(v, i) for i, v in enumerate(result_li)]:
# res_dic = dict(res)
# print(dict(d))
for v in tel_dic.values():
print(v)
# 索引列表,每個索引列表v對應乙個空列表
index_li =
if len(v) > 1:
for i in v:
if "成功" in index_li:
for i in v:
result_li[i] = "成功"
# 複製原檔案
f = open(file, encoding='gbk')
# 1.newline=''消除空格行
path01 = os.path.join(os.getcwd(), 'new_csv')
if not os.path.exists(path01):
os.mkdir(path01)
path02 = os.path.join(path01, file)
aim_file = open(path02, 'w', newline='', encoding='gbk')
write = csv.writer(aim_file)
reader = csv.reader(f)
# for row in reader:
# row[6] = result_li[i]
rows = [row for row in reader]
# print(type(rows))
print(rows)
# 2.遍歷rows列表
x = 0
for row in rows:
try:
row[6] = result_li[x]
# 3.把每一行寫到aim.csv中
write.writerow(row)
x = x + 1
except:
break
f.close()
python操作csv檔案
看上去不像是最優的樣子,可以改善 import csv csvfile open sentence lenth data.csv r encoding utf8 使用utf8格式讀取,windows預設讀取方式gbk reader csv.reader csvfile 讀取的是整張表 行 列 for...
python操作csv檔案
csv comma separated values 即逗號分隔值,可以用excel開啟檢視。由於是純文字,任何編輯器也都可開啟。與excel檔案不同,csv檔案中 值沒有型別,所有值都是字串,不能指定字型顏色等樣式,不能指定單元格的寬高,不能合併單元格沒有多個工作表,不能嵌入影象圖表 在csv檔案...
Python操作csv檔案
一 python讀取csv檔案 說明 以python3.x為例2 讀取csv檔案方法1 3import csv4 csvfile open csvwrite.csv newline 開啟乙個檔案 5 csvreader csv.reader csvfile 返回的可迭代型別 6print type ...