我正在尝试解决CS50的scourgify problem。在.csv之前的文件中有两列name和house。任务是将name列拆分为两个独立的列,即first和last。然后创建新文件并写入以下信息:第一个最后一个房子我几乎通过了所有的测试用例,但我不知道为什么我得到这个错误消息,即使我的程序给我预期的结果。
:( 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()
我检查了一些与这个问题集有关的问题,但它们没有帮助。如果有人知道问题出在哪里,我会很感激你的来信。
1条答案
按热度按时间vuv7lop31#
我发现了我的bug:
当我循环遍历每一行时,我犯了一个错误,那就是我没有分配
last, first = name.split(", ")
,而是分配了first, last = name.split(", ")
。小心像这样简单的错误,因为它花了我一段时间才找到它。