csv 无法通过scogify习题集6的CS50检查

kb5ga3dv  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(180)

我无法通过测试,即使,我的代码工作完美当我检查,
下面是我的代码..

import sys
import csv

def main():
    n, m = passing_arg()
    read_file(n, m)

def passing_arg():
    if len(sys.argv) > 3:
        sys.exit("Too many command-line arguments")

    elif len(sys.argv) < 3:
        sys.exit("Too few command-line arguments")

    elif sys.argv[1].endswith(".csv") == False or sys.argv[2].endswith(".csv") == False:
        sys.exit("Not a CSV file")

    else:
        x = sys.argv[1]
        y = sys.argv[2]
        return x, y

def read_file(x, y):
    try:
        with open(x) as file:
            content = csv.DictReader(file)
            print(type(content))
            add_header = True
            for row in content:
                last, first = row["name"].split(", ")

            with open(y, "a") as f:
                fieldnames = ['First', 'Last', 'House']
                content1 = csv.DictWriter(f, fieldnames=fieldnames)
                if add_header:
                    content1.writeheader()
                    add_header = False
                 content1.writerow({fieldnames[0] : first, fieldnames[1] : last, fieldnames[2] : row["house"]})

    except FileNotFoundError:
        sys.exit(f"Could not read {x}")

if __name__ == "__main__":
    main()

我也没有忽略空格。这就是我的代码失败的地方:link
之前:

name,house
"Abbott, Hannah",Hufflepuff
"Bell, Katie",Gryffindor
"Bones, Susan",Hufflepuff
"Boot, Terry",Ravenclaw
"Brown, Lavender",Gryffindor
"Bulstrode, Millicent",Slytherin
"Chang, Cho",Ravenclaw
"Clearwater, Penelope",Ravenclaw
"Crabbe, Vincent",Slytherin
"Creevey, Colin",Gryffindor
"Creevey, Dennis",Gryffindor
"Diggory, Cedric",Hufflepuff
"Edgecombe, Marietta",Ravenclaw
"Finch-Fletchley, Justin",Hufflepuff
"Finnigan, Seamus",Gryffindor
"Goldstein, Anthony",Ravenclaw
"Goyle, Gregory",Slytherin
"Granger, Hermione",Gryffindor
"Johnson, Angelina",Gryffindor
"Jordan, Lee",Gryffindor
"Longbottom, Neville",Gryffindor
"Lovegood, Luna",Ravenclaw
"Lupin, Remus",Gryffindor
"Malfoy, Draco",Slytherin
"Malfoy, Scorpius",Slytherin
"Macmillan, Ernie",Hufflepuff
"McGonagall, Minerva",Gryffindor
"Midgen, Eloise",Gryffindor
"McLaggen, Cormac",Gryffindor
"Montague, Graham",Slytherin
"Nott, Theodore",Slytherin
"Parkinson, Pansy",Slytherin
"Patil, Padma",Gryffindor
"Patil, Parvati",Gryffindor
"Potter, Harry",Gryffindor
"Riddle, Tom",Slytherin
"Robins, Demelza",Gryffindor
"Scamander, Newt",Hufflepuff
"Slughorn, Horace",Slytherin
"Smith, Zacharias",Hufflepuff
"Snape, Severus",Slytherin
"Spinnet, Alicia",Gryffindor
"Sprout, Pomona",Hufflepuff
"Thomas, Dean",Gryffindor
"Vane, Romilda",Gryffindor
"Warren, Myrtle",Ravenclaw
"Weasley, Fred",Gryffindor
"Weasley, George",Gryffindor
"Weasley, Ginny",Gryffindor
"Weasley, Percy",Gryffindor
"Weasley, Ron",Gryffindor
"Wood, Oliver",Gryffindor
"Zabini, Blaise",Slytherin

之后:

First,Last,House
Hannah,Abbott,Hufflepuff
Katie,Bell,Gryffindor
Susan,Bones,Hufflepuff
Terry,Boot,Ravenclaw
Lavender,Brown,Gryffindor
Millicent,Bulstrode,Slytherin
Cho,Chang,Ravenclaw
Penelope,Clearwater,Ravenclaw
Vincent,Crabbe,Slytherin
Colin,Creevey,Gryffindor
Dennis,Creevey,Gryffindor
Cedric,Diggory,Hufflepuff
Marietta,Edgecombe,Ravenclaw
Justin,Finch-Fletchley,Hufflepuff
Seamus,Finnigan,Gryffindor
Anthony,Goldstein,Ravenclaw
Gregory,Goyle,Slytherin
Hermione,Granger,Gryffindor
Angelina,Johnson,Gryffindor
Lee,Jordan,Gryffindor
Neville,Longbottom,Gryffindor
Luna,Lovegood,Ravenclaw
Remus,Lupin,Gryffindor
Draco,Malfoy,Slytherin
Scorpius,Malfoy,Slytherin
Ernie,Macmillan,Hufflepuff
Minerva,McGonagall,Gryffindor
Eloise,Midgen,Gryffindor
Cormac,McLaggen,Gryffindor
Graham,Montague,Slytherin
Theodore,Nott,Slytherin
Pansy,Parkinson,Slytherin
Padma,Patil,Gryffindor
Parvati,Patil,Gryffindor
Harry,Potter,Gryffindor
Tom,Riddle,Slytherin
Demelza,Robins,Gryffindor
Newt,Scamander,Hufflepuff
Horace,Slughorn,Slytherin
Zacharias,Smith,Hufflepuff
Severus,Snape,Slytherin
Alicia,Spinnet,Gryffindor
Pomona,Sprout,Hufflepuff
Dean,Thomas,Gryffindor
Romilda,Vane,Gryffindor
Myrtle,Warren,Ravenclaw
Fred,Weasley,Gryffindor
George,Weasley,Gryffindor
Ginny,Weasley,Gryffindor
Percy,Weasley,Gryffindor
Ron,Weasley,Gryffindor
Oliver,Wood,Gryffindor
Blaise,Zabini,Slytherin

我甚至注意到before.csv中名称之间用逗号分隔的空格,但仍然无法通过测试。

pbpqsu0x

pbpqsu0x1#

我用before.csv运行了你的代码,在after.csv中得到了这个:

First,Last,House
Blaise,Zabini,Slytherin

不过,我不确定这是否是自动检查器不满意的地方:

:(scourgify.py清除短CSV文件
原因scourgify.py未生成指定格式的CSV日志

running python3 scourgify.py before.csv after.csv...
checking that program exited with status 0...
checking that after.csv exists...

回到我在CSV中只得到一行输出的问题,可能是代码的复制-粘贴引入了缩进错误,该错误改变了程序的含义,并且只向输出CSV写入了一行。如果您回头查看发布的代码,并且缩进与预期相符,则需要重新考虑如何读取、处理和写入行。
对于我自己日常使用的Python csv模块,我喜欢把所有的行读入一个列表,然后处理这些行,再把它们写出来。

all_rows = []
with open("before.csv", newline="") as f:
    reader = csv.DictReader(f)
    all_rows = list(reader)

processed_rows = []
for row in all_rows:
    pass  # Do something with row and build up processed_rows

with open("after.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=processed_rows[0])
    writer.writeheader()
    writer.writerows(processed_rows)

附加到CSV可能会变得混乱,所以我在编写之前确保所有行都准备好了,以避免出现这种情况。
祝你好运!:)

p3rjfoxz

p3rjfoxz2#

您发布的代码中有3个错误。根据您的“完美工作”评论,我认为前1个错误可能是您将代码复制到问题中时的格式错误。其他2个错误需要解决,您的代码才能通过。(仅供参考,当我修复所有3个错误时,check 50通过。)错误是:
1.打开文件和写入时缩进不正确
1.标题行不正确(大小写错误)
1.打开写文件时文件模式“a”的使用不正确
下文提供了对每一项的详细解释。

1.不正确的缩进(见第32-38行)。@Zach Young的答案显示了你的缩进错误(如张贴的)。打开“之前”文件,读取所有行,然后打开“之后”文件,只写入2行(标题和最后一行)。

for row in content:
    last, first = row["name"].split(", ")

    with open(y, "a") as f:
        fieldnames = ['First', 'Last', 'House']
        content1 = csv.DictWriter(f, fieldnames=fieldnames)
        if add_header:
            content1.writeheader()
            add_header = False
            content1.writerow({fieldnames[0] : first, fieldnames[1] : last, fieldnames[2] : row["house"]})

**2.标题行大小写。**这个很简单。阅读说明以确认。

fieldnames = ['First', 'Last', 'House']
should be:
fieldnames = ['first', 'last', 'house']

**3.不正确地使用文件模式“a”。**这是一个细微的错误。如果只运行一次程序,您将检测不到错误。使用相同的命令行文件名运行两次,则“after”文件将是原来的两倍长。发生这种情况是因为追加模式不断地向现有文件添加内容。

有多种方法可以解决这个问题。可以使用文件模式变量add_header,或者根据add_header的值使用不同的open()行。但是,解决这个问题的最简单的方法是切换你的内部和外部循环。2目前你在“之前”文件上循环,然后在阅读每一行后必须打开并写入“之后”文件。反转它们:首先打开“after”文件(一次),然后打开“before”文件,从“before”中读取行并写入“after”。2这些方法都可以。3关键是当你多次运行程序时,不要将行追加到现有文件中。
正如我上面提到的,我修复了所有的3个错误,运行了check 50,它通过了所有的测试。顺便说一句,当测试说你有一个错误,你有一个错误。换句话说,代码没有“完美地工作”。这是开发人员的责任来找到和修复它们。这需要勤奋的诊断和谦逊。祝你好运。

相关问题