我想创建一个拥有多个用户的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()
答案 0 :(得分: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
答案 1 :(得分:0)
请
Email_Address = 'Last_Name' [("@myemail.com")]
到
Email_Address = [x + "@myemail.com" for x in Last_Name]
根据所有姓氏创建所有电子邮件地址的列表。这假设您打算将所有变量作为列表。
即使这会创建十封电子邮件(每个姓氏一封),您的文件也只会写入一行。这是因为zip
将以您传递的最短列表的长度停止迭代。目前First_Name
和Password
每个只包含一个项目。
答案 2 :(得分:0)
你的zip()只会生成一个带有1个项目的列表b / c First_Name和Password明确地每个只包含1个项目。
怎么样,完全避开拉链:
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] )