Python没有在for循环的第二个文件中读/写

2024-03-29 06:06:20 发布

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

我试图阅读两个文件,并打印在另外两个单独的文件后,阅读和作出一些更新。我的输入文件名是big-1.csv和big-2.csv。因此,我试图读取这两个文件使用for循环。对于输出我试图打印他们的名字fix-1.csv和fix-2.csv,但似乎我的For循环不是第二次运行,只运行了一次,而只是读写第一个大1.csv文件fix-1.csv文件

我的代码是:

import csv
from csv import DictWriter

for i in range(1,2):    
        print(i) #just a flag to check
        with open("big-" + str(i) + ".csv") as people_file:
            next(people_file)
            corrected_people = []
            for person_line in people_file:
                chomped_person_line = person_line.rstrip()
                person_tokens = chomped_person_line.split(",")

                # check that each field has the expected type
                try:
                    corrected_person = {
                    "id": person_tokens[0],
                    "first_name":person_tokens[1],
                    "last_name": "".join(person_tokens[2:-3]),
                    "email":person_tokens[-3],
                    "gender":person_tokens[-2],
                    "ip_address":person_tokens[-1]  

                    }

                    if not corrected_person["ip_address"].startswith(
                            "") and corrected_person["ip_address"] !="n/a":
                        raise ValueError

                    corrected_people.append(corrected_person)
                except (IndexError, ValueError):
                    # print the ignored lines, so manual correction can be performed later.
                    print("Could not parse line: " + chomped_person_line)

        with open("fix-" + str(i) + ".csv", "w") as corrected_people_file:
            writer = DictWriter(
            corrected_people_file,
            fieldnames=[
                        "id","first_name","last_name","email","gender","ip_address"
                ],delimiter=',')
            writer.writeheader()
            writer.writerows(corrected_people)

我得到的结果是:

j:\Programs\Python>python "for loop testing.py"
1

j:\Programs\Python>

和fix-1.csv文件。更新部分工作正常。我面临的唯一问题是for循环只运行一次。请注意,不会出现缩进错误。请帮忙


Tags: 文件csvnameipforaddresslinefix