读取CSV,使用随机生成的密码添加列,Python

时间:2015-09-19 08:06:48

标签: python csv

首先让我解释一下我想做的事情:

我想阅读带有用户名的CSV文件。然后,我想在用户名旁边的列中为每个用户提供一个随机生成的密码。

完成后,我想将每一行(用户名和密码)提取到一个新文档,用户名为标题。

到目前为止,这是我的代码;

    #AutogeneratePassword
import csv
import string
import random
def id_generator(size=8, chars=string.ascii_uppercase + string.ascii_lowercase + string.digits):



    with open('/home/hoss/usernames.csv', 'r') as csvinput:
        with open('/home/hoss/usernameandpassword.csv', 'w') as csvoutput:
            writer = csv.writer(csvoutput, lineterminator='\n')
            reader = csv.reader(csvinput)

            all = []
            row = next(reader)
            row.append(id_generator)
            all.append(row)

            for row in reader:
                row.append(row[0])
                all.append(row)

            writer.writerows(all)

当我运行代码时,我没有收到任何错误,但它没有将任何密码附加到我的CSV文件中。

编辑:

现在,我希望脚本在添加密码之前也检查重复项。到目前为止,这是我的代码;

    # -*- coding: iso-8859-15 -*-
import csv
import string
import random
import sys
import time
import os

os.system('clear')

print ("CSV-password generator for usernames")

print ("First, cleaning sourcefile for duplicates")

with open('UsernamesRawfile.csv') as csvdirtyinput:
    with open('UsernamesCleanfile.csv') as csvcleanoutput:
        writer = csv.writer(csvcleanoutput, lineterminator='\n')
        reader = csv.reader(csvdirtyinput)

        all = []

        for row in reader:
            if row[0] not in all:
                writer.writerow(row)
                usernames.add( row[0] )


print ("Success, file cleaned")

length = input("Password length?")

def id_generator(size=length, chars=string.ascii_uppercase + string.ascii_lowercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

with open('UsernamesCleanfile.csv', 'r') as csvinput:                                           
    with open('MasterlistUserPass.csv', 'w') as csvoutput:                                          
        writer = csv.writer(csvoutput, lineterminator='\n')                                         
        reader = csv.reader(csvinput)

        all = []                                                                                    

        for row in reader: 
            row.append(id_generator())                                                              
            all.append(row)

        writer.writerows(all)



print ("")
print ("Passwords generated")

我收到以下错误:

Traceback (most recent call last):
  File "AutoPassCSV2.py", line 24, in <module>
    writer.writerow(row)
IOError: File not open for writing

1 个答案:

答案 0 :(得分:0)

以下代码应该可以正常工作 -

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
                android:oneshot="true">

        <item android:drawable="@drawable/image1" android:duration="200" />

        <item android:drawable="@drawable/image2" android:duration="200" />

        <item android:drawable="@drawable/image3" android:duration="200" />

</animation-list>