Python | 读取CSV文件 (educoder)
任务:编写一个能读取csv文件的程序,将指定的文件按照要求的格式输出。
要求:在你的程序的当前目录下存在一个book.csv文件,读取该文件的内容,并输出要求的内容和格式。
第一关:
说明: 预期输出:
书名 python程序设计 数据结构 C语言程序设计
代码:
import csv
def readcsv():
# *************begin************#
csvfile = open(book.csv,r,encoding= utf-8)
csvreader = csv.reader(csvfile)
for row in csvreader:
print(row[0])
csvfile.close()
# **************end*************#
if __name__ == __main__:
readcsv()
第二关:
说明: 预期输出:
[python程序设计, 39] [数据结构, 49] [C语言程序设计, 42]
代码:
import csv
def readcsv():
# *************begin************#
fc = open(book.csv,r,encoding= utf-8)
lst = []
for line in fc:
line = line.replace(
,)
lst.append(line.split(,))
for i in range(1,len(lst)):
print(lst[i])
fc.close()
# **************end*************#
if __name__ == __main__:
readcsv()
第三关:
说明: 预期输出:
[{书名: python程序设计, 价钱: 39}, {书名: 数据结构, 价钱: 49}, {书名: C语言程序设计, 价钱: 42}]
代码:
import csv
def readcsv():
# *************begin************#
csvfile = open(book.csv, r, encoding=utf-8)
csvreader = csv.DictReader(csvfile)
lst = []
for i in csvreader:
i = dict(i)
lst.append(i)
print(lst)
csvfile.close()
# **************end*************#
if __name__ == __main__:
readcsv()
