如何防止我的csv_writer变量阻止我的代码的阅读部分正确运行?

9rnv2umw  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(117)

我试图创建一个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)
0g0grzrc

0g0grzrc1#

你没有关闭你的文件正确与csv_file.close vs csv_file.close() .还有一些其他的缩进问题,但也许这只是由于网站。
工作修订:https://onlinegdb.com/kdB73BBAi

import csv

# Writing to CSV files
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()

# Reading CSV files
names_list = []
csv_file = open("names.csv", "r", newline = "")
csv_reader = csv.reader(csv_file, delimiter = ",", quotechar = "|")
for data in csv_reader:
    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)

相关问题