没有创建CSV文件时出现问题


chars = list(range(0,10)) 
numbers_list = list(range(0,25))
for comb in itertools.combinations_with_replacement(chars, 5): 
for A in numbers_list:
pure = str(A) + ':' + str(comb) 
B = pure.replace(")", "").replace("(", "").replace("'", "").replace(",", "").replace(" ", "") 
C = hashlib.sha256(B.encode('utf-8')).hexdigest()
rows = [A , str(B), str(C)]
print(rows)
header = ['A', 'B', 'C'] 
with open('data.csv', 'w', encoding='UTF8', newline='') as f: 
writer = csv.writer(f)
writer.writerow(header)
writer.writerow(rows) 
print('end')

大家下午好,我遇到csv文件未创建的问题。这些行在IDE中打印出来,但当脚本在几个小时后运行完组合的所有行时,它不会创建包含这些行的CSV文件。我对python编程有点陌生。我真的很感激你的帮助!非常感谢。

John Gordon是正确的,您需要保留列表中的每一行,然后在将每一行写入csv文件时循环该列表

这个脚本适用于我

import itertools, hashlib, csv
data = []
chars = list(range(0,10)) 
numbers_list = list(range(0,25))
for comb in itertools.combinations_with_replacement(chars, 5): 
for A in numbers_list:
pure = str(A) + ':' + str(comb) 
B = pure.replace(")", "").replace("(", "").replace("'", "").replace(",", "").replace(" ", "") 
C = hashlib.sha256(B.encode('utf-8')).hexdigest()
rows = [A , str(B), str(C)]
data.append(rows)

header = ['A', 'B', 'C'] 
with open('data.csv', 'w', encoding='UTF8', newline='') as f: 
writer = csv.writer(f)
writer.writerow(header)
for row in data:
writer.writerow(row) 
print('end')

我建议采用一种更简单的方法。你有没有考虑过用熊猫模块来做这种工作?Pandas模块将让您更容易地保存csv、xls。。。试试看。

import itertools
import hashlib
import pandas as pd
chars = list(range(0,10))
numbers_list = list(range(0,25))
rows = []
for combination in itertools.combinations_with_replacement(chars, 5):
for number in numbers_list:
pure_number_a = str(number) + ':' + str(combination) 
pure_number_b = pure_number_a.replace(")", "").replace("(", "").replace("'", "").replace(",", "").replace(" ", "") 
pure_number_c = hashlib.sha256(pure_number_b.encode('utf-8')).hexdigest()
rows.append([pure_number_a , pure_number_b, pure_number_c])

df = pd.DataFrame(data=rows, columns=['A', 'B', 'C'])
df.to_csv('data.csv', index=False)

相关内容

  • 没有找到相关文章

最新更新