读写CSV 文件
第三方库CSV中提供了2个类来写CSV文件
- csv.writer class
csv.writer class provides two methods for writing to CSV. They are writerow() and writerows().
writerow(): This method writes a single row at a time. Field row can be written using this method.
Syntax:
writerow(fields)
writerows(): This method is used to write multiple rows at a time. This can be used to write rows list.
Syntax:
Writing CSV files in Python
writerows(rows)
- csv.DictWriter class
csv.DictWriter provides two methods for writing to CSV. They are:
writeheader(): writeheader() method simply writes the first row of your csv file using the pre-specified fieldnames.
Syntax:
writeheader()
writerows(): writerows method simply writes all the rows but in each row, it writes only the values(not keys).
Syntax:
writerows()
同样,在读CSV文件时,也可以用 csv.DictReader() class和csv.reader()来读
import csv
def WriterCSV():
fields = ['Name', 'Branch', 'Year', 'CGPA']
rows = [['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1']]
filename = "test1.csv"
with open(filename, 'w', newline='') as csvfile:
# 在以这种方法写CSV时,需要加newline='',否则读CSV时,会有多个空列表,原因待确定
# creating a csv writer object
csvwriter = csv.writer(csvfile)
# writing the fields
csvwriter.writerow(fields)
# writing the data rows
csvwriter.writerows(rows)
def writerSCVDict():
mydict = [{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'},
{'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'},
{'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'},
{'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'},
{'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'},
{'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}]
fields = ['name', 'branch', 'year', 'cgpa']
filename = "test2.csv"
with open(filename, 'w') as csvfile:
# creating a csv dict writer object
writer = csv.DictWriter(csvfile, fieldnames=fields)
# writing headers (field names)
writer.writeheader()
# writing data rows
writer.writerows(mydict)
def ReadingCSV():
import csv
# opening the CSV file
with open('test1.csv', mode='r')as file:
# reading the CSV file
csvFile = csv.reader(file)
# displaying the contents of the CSV file
for lines in csvFile:
# if lines != '\n':
print(lines)
def DictReaderCSV():
import csv
# opening the CSV file
with open('test2.csv', mode='r') as file:
# reading the CSV file
csvFile = csv.DictReader(file)
# displaying the contents of the CSV file
for lines in csvFile:
print(lines)
参考博客:
https://www.geeksforgeeks.org/reading-csv-files-in-python/?ref=lbp
https://www.geeksforgeeks.org/writing-csv-files-in-python/?ref=lbp

浙公网安备 33010602011771号