无法创建CSV文件

hfyxw5xn  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(234)
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编程有点陌生。我真的很感激你的帮助!谢谢!

56lgkhnf

56lgkhnf1#

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')
pxq42qpu

pxq42qpu2#

我会建议一个更简单的方法。你有没有考虑过用Pandas模块来做这类工作?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)

相关问题