将列表内容写入csv fi

2024-04-27 04:20:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用下面的代码将列表的内容写入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

等等

我尝试了不同的分隔符选项,甚至尝试了它没有,但我没有太多的成功。任何指向正确方向的指示都将不胜感激。你知道吗


Tags: 文件csv代码text列表记录greenblue
1条回答
网友
1楼 · 发布于 2024-04-27 04:20:59

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

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文件,它可以工作,但不会写入最后一列。你知道吗

谢谢你的指点。你知道吗

谢谢

相关问题 更多 >