我试图创建一个csv文件,并在阅读该文件之前存储姓名,电子邮件地址和电话号码,并将数据放入列表并输出。但是,如果我不将csv_writer变量改写为空(csv_writer =“”),则阅读部分不会遍历文件,而是跳过并输出一个空列表。这个csv_writer变量不为空的存在导致我的csv_reader变量被保存而<_csv.reader object at 0x0000019A529D7EE0>不是<_csv.Dialect object at 0x000002C86E6921C0>。我的代码在下面,如果它有帮助的话。
# Writing to CSV files
import csv
headings = ["Name", "Email", "Phone"]
names_list = [["Fred","[email protected]","01909-9098645"], ["Sue","[email protected]","01986-3937586"], ["John","[email protected]","01892-3983753"], ["Beth","[email protected]","230492843"], ["beth","bth@3409ldf","3098430432"], ["Bob","[email protected]","2304982304"], ["Joe","joe*0394","230482304"]]
csv_file = open("names.csv", "w", newline = "")
csv_writer = csv.writer(csv_file, delimiter = ",", quotechar = "|")
csv_writer.writerow(headings)
for data in names_list:
csv_writer.writerow(data)
csv_file.close
csv_writer = "" # Removing this causes the following code to malfunction (outputting [])
# Reading CSV files
import csv
names_list = []
csv_file = open("names.csv", "r", newline = "")
csv_reader = csv.reader(csv_file, delimiter = ",", quotechar = "|")
for data in csv_reader: # This is the loop which gets skipped when csv_writer doesn't get overwritten
if csv_reader.line_num == 1:
headings = [data[0], data[1], data[2]]
else:
name = [data[0], data[1], data[2]]
names_list.append(name)
csv_file.close
print(names_list)
1条答案
按热度按时间0g0grzrc1#
你没有关闭你的文件正确与
csv_file.close
vscsv_file.close()
.还有一些其他的缩进问题,但也许这只是由于网站。工作修订:https://onlinegdb.com/kdB73BBAi