Home > Mobile >  Having an issue with CSV file not creating
Having an issue with CSV file not creating

Time:11-06

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

Good afternoon everyone, I am having an issue with csv file not being created. The rows are printing out in IDE, but when the script is done running all the rows of combinations after a few hours, it does not create the CSV file with the rows. I am bit new to programing in python. I would be really appreciative the help! Thank you!

CodePudding user response:

John Gordon is correct, you need to retain each row in a list, then loop through that list when writing each row to the csv file

this script works for me

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

CodePudding user response:

I would suggest a much more simple approach. Did you ever considered to use the pandas module for this kind of job? Pandas module will let you save much more easier to csv, xls... Give it a try.

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)
  • Related