:(scourgify.py 清理短 CSV 文件 ||:|scourgify.py 清理长 CSV 文件

:( scourgify.py cleans short CSV file || :| scourgify.py cleans long CSV file

提问人:Sunnat Amirov 提问时间:8/9/2023 更新时间:8/9/2023 访问量:478

问:

我正在尝试解决 CS50 的祸害问题。在名为 before.csv 的文件中,有两列分别是 name、house。任务是将名称列拆分为两个独立的列,即第一列和最后一列。然后创建新文件并写入以下信息:first、last、house。我几乎通过了所有测试用例,但我不知道为什么我会收到此错误消息,即使我的程序给了我预期的结果。

:( scourgify.py cleans short CSV file
Cause
scourgify.py does not produce CSV with specified format
Log
running python3 scourgify.py before.csv after.csv...
checking that program exited with status 0...
checking that after.csv exists...
:| scourgify.py cleans long CSV file
Cause
can't check until a frown turns upside down

这是我的整体代码实现:

import sys
import csv


def main():
    if len(sys.argv) >= 4:
        print("Too many command-line arguments")
        sys.exit(1)

    if len(sys.argv) <= 2:
        print("Too few command-line arguments")
        sys.exit(1)

    filepath1 = sys.argv[1]
    filepath2 = sys.argv[2]
    if not filepath1.endswith(".csv") or not filepath2.endswith(".csv"):
        print("Not a CSV file")
        sys.exit(1)

    data = read_from_file(filepath1)
    writer = write_to_file(filepath2, data)

def read_from_file(filepath):
    updated_data = []
    try:
        with open(filepath, "r") as file:
            data = csv.DictReader(file)

            for i in data:
                name = i["name"]
                house = i["house"]
                first, last = name.split(", ")
                new_dict = {
                    "first": first,
                    "last": last,
                    "house": house,
                }
                updated_data.append(new_dict)

    except FileNotFoundError:
        print("File does not exist")
        sys.exit(1)

    return updated_data


def write_to_file(filepath, new_data):
    fieldnames = ["first", "last", "house"]
    try:
        with open(filepath, mode="w") as file:
            writer = csv.DictWriter(file, fieldnames=fieldnames)
            writer.writeheader()
            writer.writerows(new_data)

    except FileNotFoundError:
        print("File does not exist")
        sys.exit(1)


if __name__ == "__main__":
    main()

我检查了与此问题集相关的一些问题,但它们没有帮助。如果有人知道问题出在哪里,我将不胜感激。

python csv 文件 read-csv

评论

0赞 Rayon Magique 8/9/2023
也许这个话题可以帮助你 reddit.com/r/cs50/comments/v4kuet/scourgify_failing_check50

答:

2赞 Sunnat Amirov 8/9/2023 #1

我发现了我的错误:

            for i in data:
            name = i["name"]
            house = i["house"]
            last, first = name.split(", ")
            new_dict = {
                "first": first,
                "last": last,
                "house": house,
            }
            updated_data.append(new_dict)

当我遍历每一行时,我犯了错误,而不是分配,我做了。小心这个简单的错误,因为我花了一些时间才找到它。last, first = name.split(", ")first, last = name.split(", ")