CSV重写器不断创建新标头

时间:2017-10-25 21:59:01

标签: python python-3.x file csv

我的代码每次创建相同的标题,我希望它创建一个并将数据附加到CSV而不创建新标题。

What it looks like in the CSV

What I want it to look like

import csv

with open("Details.csv","a+") as Details:
    w=csv.writer(Details,delimiter=",")

    headers1=["Name","Age","Year Group"]
    line=Details.readlines()
    if line!=["Name","Age","Year Group"]:
        w.writerow(headers1)
    print("Welcome User, to my Topics Quiz!\n-------------------------------
    --------\nYou can choose from 3 different topics:\n  • History\n  •
    Music\n •  Computer Science\n---------------------------------------")
    print("Before we start, we need to register an account.")
    User=input("Enter your name:\n")
    Age=input("Enter your age:\n")
    Year=input("Enter your year group:\n")

    details=[User,Age,Year]
    w.writerow(details)
    Details.close()

with open("UserPass.csv","a+") as Userpass:
    w=csv.writer(Userpass,delimiter=",")
    headers2=["Username","Password"]
    if headers2 not in Userpass:
       w.writerow(headers2)

NewUser=(User[:3]+Age)
print("Great! Your username is set to: {}".format(NewUser))
Pass=input("Enter a password for your account:\n")
userpass=[NewUser,Pass]
w.writerow(userpass)
Userpass.close()

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

您的代码中存在不同的问题:

1)csv文件中包含数据的行之间的空行,由于非二进制类型的开放而发生,可以通过在open函数中添加arg来修复:

w=csv.writer(Details,delimiter=",",lineterminator='\n')

2)在你的情况下,Details.readlines()方法返回[],因为a +类型的开放,它应该在文件的末尾添加行,所以指针已经在最后了我们需要在开头使用该代码返回它:

line=Details.seek(0)

3)另外,我们只需要第一行,所以只需使用readline()方法。毕竟,你的情况应该是这样的,因为返回类型以及每行末尾都有\ n的事实:

if line!="Name,Age,Year Group\n":

该部分的完整代码。让我知道它是否适合你:

w=csv.writer(Details,delimiter=",",lineterminator='\n')
headers1=["Name","Age","Year Group"]
line=Details.seek(0)
line=Details.readlines()[0]
print(line)
if line!="Name,Age,Year Group\n":
    w.writerow(headers1)

答案 1 :(得分:0)

您正在以附加模式(https://docs.python.org/3/library/functions.html#open)打开文件,因此此line=Details.readlines()将始终为空行,并且每次都会写入您的标题(代码将始终进入,如果)。

与其他文件类似。因此,我建议您首先检查文件是否存在,如果没有创建并添加标题,则从with删除标题部分:

import csv

import os.path
if not os.path.isfile("Details.csv"):
    with open("Details.csv", "a+") as Details:
        w = csv.writer(Details, delimiter=",")
        headers1 = ["Name", "Age", "Year Group"]
        w.writerow(headers1)
        Details.close()

if not os.path.isfile("UserPass.csv"):
    with open("UserPass.csv", "a+") as Userpass:
        w = csv.writer(Userpass, delimiter=",")
        headers2 = ["Username", "Password"]
        w.writerow(headers2)
        Userpass.close()

with open("Details.csv", "a+") as Details:
    w = csv.writer(Details, delimiter=",")
    print("Welcome User, to my Topics Quiz!\n-------------------------------"
          "--------\nYou can choose from 3 different topics:\n  • History\n  • "
          "Music\n •  Computer Science\n---------------------------------------")
    print("Before we start, we need to register an account.")
    User = input("Enter your name:\n")
    Age = input("Enter your age:\n")
    Year = input("Enter your year group:\n")

    details = [User, Age, Year]
    w.writerow(details)
    Details.close()

with open("UserPass.csv", "a+") as Userpass:
    w = csv.writer(Userpass, delimiter=",")
    NewUser = (User[:3] + Age)
    print("Great! Your username is set to: {}".format(NewUser))
    Pass = input("Enter a password for your account:\n")
    userpass = [NewUser, Pass]
    w.writerow(userpass)
    Userpass.close()

答案 2 :(得分:0)

我不了解您的代码尝试完成的所有内容,但以下内容会向Details.csv添加一行而不创建任何新标题:

import csv
import os

csv_fileheader = "Name", "Age", "Year Group"
csv_filename = "Details.csv"

print("Welcome User, to my Topics Quiz!\n"
      "---------------------------------------\n"
      "You can choose from 3 different topics:\n"
      " • History\n • Music\n • Computer Science\n"
      "---------------------------------------")
print("Before we start, we need to register an account.")
user = input("Enter your name:\n")
age = input("Enter your age:\n")
year = input("Enter your year group:\n")

if not os.path.isfile(csv_filename):  # Create file if it doesn't exist.
    with open(csv_filename, "w", newline='') as csv_file:
        csv.writer(csv_file).writerow(csv_fileheader)  # Put header row in it.

with open(csv_filename, "a+", newline='') as details2:
    writer = csv.writer(details2, delimiter=",")
    writer.writerow((user, age, year))

您应该考虑遵循PEP 8 - Style Guide for Python Code建议,因为这样可以让您和其他人更轻松地阅读您的代码。