我正在尝试读取两个文件,并在读取并进行一些更新后将它们打印在另外两个单独的文件中。我的输入文件名为big-1.csv和big-2.csv。因此,我试图使用for循环读取这两个文件。对于输出即时消息,我尝试使用名称fix-1.csv和fix-2.csv打印它们,但是看来我的for循环第二次没有运行,只运行了一次,而只读写第一个big-1。 csv文件修复为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循环仅运行一次。请注意,没有缩进错误。请帮忙。
答案 0 :(得分:2)
range(1,2)
仅包含一个值(数字1)。
也许你是说
for i in (1,2): # values are 1 and 2
或
for i in range(2): # values are 0 and 1
或
for i in range(1,3): # values are 1 and 2