-1
from hashlib import sha256
import csv

with open ('source.csv', 'r' ) as file:
    reader = csv.reader ( file )

    dic = {}
    for hash in range ( 1000, 10000):
        hasher = sha256 ( b'%i' % hash ).hexdigest ()
        hash = dic [ hasher ] = hash

    for row in reader:
        name = row [ 0 ] 
        for key in row [ 1: ]:
            hack = ( name, dic [ key ] )

        for r in hack:
            with open ( 'out.csv', 'w', newline = '' ) as out:
                writer = csv.writer ( out )
                writer.writerow ( hack )

我写的是:

peter,5104

写应该是这样的:

alex,2218
emma,4215
peter,5104
4

2 回答 2

1

好的,所以在循环的每次迭代中,for r in hack:您打开同一个文件以写入擦除以前的内容。您可以将文件的打开移到最外层循环之外。代码应该看起来像

from hashlib import sha256 import csv

with open ('source.csv', 'r' ) as file: 
    reader = csv.reader ( file )
    with open ( 'out.csv', 'w', newline = '' ) as out:
        writer = csv.writer ( out )
        for row in reader:
            name = row [ 0 ] 
            for key in row [ 1: ]:
                hack = ( name, dic [ key ] )

                for r in hack:
                    writer.writerow ( hack )

请记住,该文件对整个代码都是打开的,这有一些含义。

于 2021-06-12T11:07:55.700 回答
0

from hashlib import sha256 import csv

dic = {} hacks = []

for hash in range(1000, 10000): hasher = sha256 ( b'%i' % hash ).hexdigest () hash = dic [ hasher ] = hash

with open ('source.csv', 'r') as file: reader = csv.reader (file) for row in reader: name = row[0] for key in row[1:]: hacks.append((name, dic[key]))

with open('out.csv', 'w', newline = '') as out:`

writer = csv.writer(out)
for hack in hacks:
    writer.writerow(hack)  
out.close()
于 2021-06-13T20:21:10.687 回答