如何格式化csv文件以将所有信息放在一行上然后向下移动?



>我有一个文件,它获取信息并将其写入csv文件。 我无法让它按照我想要的方式格式化。 它循环了 10 次,我可以确认信息在那里。 我包含代码以向您展示csv编写部分的确切设置。

这是我的代码:

outfile = open('Accounts_Details.csv', 'a')
for i in range(0, 11):
#Calling all the above functions
soc_auth_requests()
create_account()
config_admin_create()
account_user_create()
account_activate()
account_config_DNS_create()
#Creating the dictionary for the CSV file with the data fields made and modified from before
#It is necessary this be done after the above method calls to ensure the data field values are correct
data = {
'Account_Name': acc_name,
'Account_Id': acc_id,
'User_Email': user_email,
'User_id': user_id
}
#Creating a csv file and writing the dictionary titled "data" to it
for key, value in sorted(data.items()):
outfile.write('t' + str(value))
outfile.write('n')

所以我在字典中有四位数据,我希望格式在 csv 文件中布局,以便将四位信息放在一行上,当它循环通过 for 循环时,它会移动到下一行并在那里做同样的事情。

前任。

name1, id1, email1, uId1
name2, id2, email2, uId2
name3, id3, email3, uId3

我认为这与我打开文件的方式有关,但我不确定也无法弄清楚。

感谢您的帮助!

这是我得到的当前输出。 我希望所有的 1 都在一行上,然后向下移动。

name1
id1
email1
uID1
name2
id2
email2
uID2

尝试从最后一个语句中删除参数:

for key, value in sorted(data.items()):
outfile.write('t' + str(value))
# outfile.write('n')
# modified for
outfile.close()

请让我知道它是怎么回事,如果这有效! :)

我不认为你的文件打开参数是问题所在——我无法复制这个问题。但是,您可以通过对数据使用列表推导式来简化代码并消除任何问题的可能性:

for i in range(12):
data = {
'Account_Name': 'AccountName',
'Account_Id': '#12345',
'User_Email': 'a@b',
'User_id': 'LOGGER'
}
with open("test.txt", "a") as f:
f.write('{}n'.format(', '.join(data.values())))

只需使用 csv 模块,它将自动为您格式化行:

outfile = open('Accounts_Details.csv', 'a')
writer = csv.DictWriter(outfile, [ 'Account_Name', 'Account_Id', 'User_Email', 'User_id' ])
# optionaly if you want a header line:
writer.writeheader()
for i in range(0, 11):
...
data = {
'Account_Name': acc_name,
'Account_Id': acc_id,
'User_Email': user_email,
'User_id': user_id
}
writer.writerow(data)
outfile.close()

相关内容

最新更新