-1

我想创建一个包含多个用户的 csvfile,同时使用他们的姓氏为这些用户创建电子邮件地址。我为此使用python,但无法在列表中创建电子邮件地址。我的脚本在下面,我错过了什么?

import csv

First_Name = ["Test"]
Last_Name = ["User%d" % i for i in range (1,10)]
Email_Address = 'Last_Name' [("@myemail.com")]
Password = ["Password1"]

# open a file for writing.
csv_out = open('mycsv.csv', 'wb')

# create the csv writer object.
mywriter = csv.writer(csv_out)

# all rows at once.
rows =zip(Email_Address, Password, First_Name, Last_Name,)
mywriter.writerows(rows)

csv_out.close()
4

3 回答 3

0

我基本上是在猜测,因为你没有说你遇到了什么错误,但我能看到的最明显的问题是你试图将一个字符串添加到一个元组列表中,这不会产生很有意义。

'Last_Name' [("@myemail.com")]

应该:

'Last_Name' + "@myemail.com"

现在,就您实际尝试做的事情而言,这是非常不清楚的,我认为您想使用一系列列表推导。例如:

users = [i for i in range(0, 10)]
first_names = ["test"+str(user) for user in users]
last_names = ["User%d" %user for user in users]
email_addresses = [last_name + "@myemail.com" for last_name in last_names]
passwords = ["Password1" for user in users]

with open('mycsv.csv', 'wb') as csv_out:
    writer = csv.writer(csv_out)
    writer.writerows(zip(email_addresses, passwords, first_names, last_names))

输出:

User0@myemail.com,Password1,test0,User0
User1@myemail.com,Password1,test1,User1
User2@myemail.com,Password1,test2,User2
User3@myemail.com,Password1,test3,User3
User4@myemail.com,Password1,test4,User4
User5@myemail.com,Password1,test5,User5
User6@myemail.com,Password1,test6,User6
User7@myemail.com,Password1,test7,User7
User8@myemail.com,Password1,test8,User8
User9@myemail.com,Password1,test9,User9
于 2013-07-03T15:29:34.933 回答
0

Make

Email_Address = 'Last_Name' [("@myemail.com")]

into

Email_Address = [x + "@myemail.com" for x in Last_Name]

to create a list of all email addresses based on all last names. This assumes you intended for all of your variables to be lists.

Even though this will create ten emails (one for each last name) your file will only have one row written to it. This is because zip will stop iteration at the length of the shortest list you pass it. Currently First_Name and Password each contain only one item.

于 2013-07-03T15:31:13.760 回答
0

Your zip() will only produce a list w/ 1 item b/c First_Name and Password explicitly each contain only 1 item.

How about this, avoiding the zip entirely:

with open('mycsv.csv', 'wb') as csv_out:
    writer = csv.writer(csv_out)
    for i in xrange(1,9):
        writer.writerow( ["User%d@myemail.com"%i, "Password%d"%i, "test%d"%i, "User%d"%i] )
于 2013-07-03T15:32:03.950 回答