Python CSV读写

时间:2020-02-23 14:42:34  来源:igfitidea点击:

在本教程中,我们将了解python已经存在的python csv模块。
在之前的教程中,我们看到了python mysql示例。

Python CSV

CSV代表逗号分隔的值。
在本教程中,我们将看到如何在python中读取和写入CSV文件。
Python提供了一个名为csv的模块,使用它我们可以对csv文件进行一些操作。

Python CSV文件

如我之前所说,CSV是一种文件格式。
Python CSV模块将有助于读取和写入csv文件。

以下是csv文件的示例。
文件名为" employeeInfo.csv",该文件取自包含员工姓名,部门和电子邮件地址信息的excel工作表。

employeeInfo.csv

Employee Name,Department,Email Address
Rizvi,MEC,[email protected]
Mamun,EECE,[email protected]
Shamsujjaman,CSC,[email protected]
Anika,ECE,[email protected]
Zinia,CSE,[email protected]
Nazrul,AE,[email protected]

我们必须将此csv文件保存在我们要使用python访问该文件的目录中。

Python读取CSV

借助于csv.reader()方法,我们可以按如下方式读取csv文件的内容。

#importing csv
import csv

#openning the csv file which is in the same location of this python file
File = open('employeeInfo.csv')

#reading the File with the help of csv.reader()
Reader = csv.reader(File)

#storing the values contained in the Reader into Data
Data = list(Reader)

#printing the each line of the Data in the console
for data in Data:
 print(data)
File.close()

下图显示了以上python csv read示例程序产生的输出。

因此,我们已经阅读了csv文件。
如果我们想获取诸如姓名和电子邮件地址之类的特定列怎么办?然后,我们必须执行以下操作:

#importing csv
import csv

#openning the csv file which is in the same location of this python file
File = open('employeeInfo.csv')

#reading the File with the help of csv.reader()
Reader = csv.reader(File)

#storing the values contained in the Reader into Data
Data = list(Reader)

#printing the 0th and 2nd column of each line of the Data in the console
for data in Data:
 print(data[0],' | ', data[2])
File.close()

它只会输出员工的姓名和电子邮件地址。

Python CSV编写器

您也可以使用python csv模块在csv文件中写入。
要写入文件,您可以以写入模式打开文件,也可以以追加模式打开文件。

然后,您必须使用pythoncsv.writer()来写入csv文件。
以下是写入名为output.csv的csv文件的示例。

#importing csv
import csv
# opening a file in write mode and newline = ''
# otherwise output.csv will contain two newline after writing each line.
File = open('output.csv', 'w', newline ='')

# setting the writer to the File
Writer = csv.writer(File)

# writing some values
Writer.writerow(['Yantai' , 'Resturant'])
Writer.writerow(['Convension Hall' , 'Community Center'])
Writer.writerow(['Lalbag Kella' , 'Historical Architecture'])

# closing the file
File.close()

现在,您将在同一目录中看到一个名为" output.csv"的文件。
打开该文件,您将找到其中写入的值。