将列表的内容写入csv文件

时间:2017-11-09 13:53:03

标签: python list csv export-to-csv

我使用下面的代码将list的内容写入csv文件。

    import csv

    text_file = open("memberstest.txt", "r")
    lines = text_file.read().split(' ')
    print(lines)


    myfile = open('members.csv','w')
    wr = csv.writer(myfile, delimiter=" ")
    wr.writerows(lines)
    myfile.close()

我遇到的问题是每个单词都写入一个新行而不是将每个记录保存在一个单独的行上。例如,我的列表如下所示:

["['user1',", "'01/01/01',", "'blue',", "'green'['user2',", "'12/12/12',", "'pink',", "'orange']['user3',", "'03/03/03',", "'purple',", "'green']"] 

当我执行我的代码时,我的csv文件看起来像:

[ ' u s e r 1 ' 

' 0 1 / 0 1 / 0 1 ' 

' b l u e ' 

' g r e e n ' ] [ ' u s e r 2 ' 

' 1 2 / 1 2 / 1 2 ' 

' p i n k ' 

' o r a n g e ' ] [ ' u s e r 3 ' 

' 0 3 / 0 3 / 0 3 ' 

' p u r p l e ' 

' g r e e n ' ]

在每个单词之后留下一个行间隙,并且它连接在一起的每个记录中的最后一个项目和第一个项目。

我希望看到的是:

user 1   01/01/01   blue  green
user 2   12/12/12   pink   orange

我已经为分隔符尝试了不同的选项,甚至尝试了它,但我没有取得多大成功。任何指向正确方向的人都会非常感激。

1 个答案:

答案 0 :(得分:0)

我首先将新用户写入文本文件:

import time
import csv

    account = input("Do you want to create an OCRtunes account? Y/N  ")
    if account == "Y" or account == "y":

        adduser = []
        user = str(input("enter user: "))
        adduser.append(user.strip())
        print("----------------------------------------------")
        username = input("enter your username: ")
        adduser.append(username.strip())
        print("-----------------------------------------------")
        password = input("enter password: ")
        adduser.append(password.strip())
        print("------------------------------------------------")
        rights = input("enter admin or client: ")
        adduser.append(rights.strip() + "\n")
        print(adduser)
        -------------------")
        reply = input("Do you want these details to be saved? ")

        if reply =="Y" or reply =="y":

            with open('memberstestv2.txt', 'a') as f:
                str(adduser)
                f.writelines(",".join(adduser))
                print (adduser)
                f.close()

            print("User created")

memberstest2.txt文件中的详细信息保存为:

user1,username1,password1,admin
user2,username2,password2,access
user3,username3,password3,access

然后,当我想编辑用户的密码并回写到同一个文件或新的csv文件时,我会这样做:

with open('memberstestv2.txt') as fo:
    user = []
    updated_list = []

    for rec in fo:
        user.append(rec.split(','))

    print(user)
    username=input("Enter username: ")

    for row in user:
        for field in row:
            if username == field:
                updated_list.append(row)
                print("user found")
                password = input("enter new password: ")
                updated_list[0][2] = password
                print(updated_list)

                for index, row in enumerate(user):
                    for field in row:
                        if field == updated_list[0]:
                            user[index] = updated_list # Replace old record with updated record.


                with open("memberstestv2.txt","w", newline='') as f:
                    Writer=csv.writer(f)
                    Writer.writerows(user)
                    print("password has been updated")

                exit

在控制台中,这就是输出的外观:

[['user1', 'username1', 'password1', 'admin\n'], ['user2', 'username2', 'password2', 'access\n'], ['user3', 'username3', 'password3', 'access']]
Enter username: user1
user found
enter new password: new password
[['user1', 'username1', 'new password', 'admin\n']]
password has been updated

但是,在文本文件中,数据在最后一项附近用引号保存,如:

user1,username1,new password,"admin
"
user2,username2,password2,"access
"
user3,username3,password3,access

如果我继续更新另一个密码,控制台中的结果是:

[['user1', 'username1', 'new password', '"admin\n'], ['"\n'], ['user2', 'username2', 'password2', '"access\n'], ['"\n'], ['user3', 'username3', 'password3', 'access\n']]
Enter username: user2
user found
enter new password: new password 2
[['user2', 'username2', 'new password 2', '"access\n']]
password has been updated

在文本文件中,它保存为:

user1,username1,new password,"""admin
"
"""
"
user2,username2,new password 2,"""access
"
"""
"
user3,username3,password3,"access
"

每次更新密码时似乎都会添加引号。如果我尝试写入csv文件,它可以工作,但不会写最后一列。

任何指示赞赏。

由于