如何在python中写入csv文件时跳过使用过的行或继续直到未使用的行?

时间:2017-07-27 16:58:41

标签: python csv

我正在尝试将信息写入csv文件。它位于for循环中,将改变数据。基本上我想要它做的是将数据放入csv文件然后它将循环获取新数据并将其放在相同的csv文件中,但它需要继续从最后一组数据停止的地方而不是替换它。

这就是我所拥有的:

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

    outfile = open('Accounts_Details.csv', 'w')
    while('Accounts_Details.csv'.isspace() == False):
        outfile.readline()
    for key, value in sorted(data.items()):
        outfile.write('\t' + str(value) + '\n')

我不能提供更多,但我可以确认它正在解析10次而且数据就在那里。如何跳过使用的线路或继续我离开的地方?

注意:每一位信息都必须在换行符上。例如:

id1
name1
id2
name2
.
.
.

注意:我尝试了很多不同的线程,但没有一个适用于我的情况,也没有足够的解释让我匹配它们,所以我一直在探索没有运气的选项。

2 个答案:

答案 0 :(得分:1)

您可以在打开文件时使用附加'a'修饰符来写入您离开的位置。例如:

outfile = open('Accounts_Details.csv', 'a')
for key, value in sorted(data.items()):
    outfile.write('\t' + str(value) + '\n')

答案 1 :(得分:1)

打开for循环外的文件

with open(filepath, 'w') as f:
    for i in range(something):
        d = create_dict()
        for a, b in d.items():
            f.write('{}\t{}\n'.format(a, b)