1.CSV格式
CSV(Comma-Separated Values)是一种通用的、相对简单的文件格式
在商业和科学领域上广泛使用
规则
以行为单位
每行表示一条记录
以英文逗号分割每列数据(如果数据为空,逗号也要保留)
列名通常放置在文件第一行
2.CSV文件操作
方法一:使用csv库读取csv文件
Import csv
读文件的时候,打开文件,调用csv.reader()读取文件;对于读取之后的文件的内容,要把这些内容输入到另一个文件中保存,可以通过遍历读取的文件的每一行,然后使用csv_write.writerow()的方式写入到指定的文件。
csv_file = open(filename,mode=‘r’,encoding=‘utf-8’)
reader=csv.reader(csv_file)
for item in reader:
print(item)
csv_file.close()
with open(filename,'r') as csvFile:
reader2 = csv.reader(csvFile)
for item2 in reader2:
print(item2)
csvFile.close()
import csv
filename = './files/menu.csv'
csvFile2 = open(filename,'r',newline='')
writer = csv.reader(csvFile2)
print(writer)
for i in writer:
print(i)
csvFile2.close()
#从字典写入csv文件
dic = {'张三':123,'李四':456,'王二娃':789}
csvFile3 = open(filename,'w',newline='')
writer2 = csv.writer(csvFile3)
for key in dic:
print(key)
writer2.writerow([key,dic[key]])
csvFile3.close()
应用实例(将空气质量的JSON文件读出后,写入到CSV文件)
方法二:使用pandas库读写csv文件(csv文件是gbk编码)
import pandas as pd
df=pd.read_csv(filename) #读取csv文件到dataframe中,默认读取以逗号为分割符的文件
df=pd.read_table(filename,sep=‘,’) #read_table默认读取分隔符为制表符的文件
df.to_csv(filename) #将dataframe数据写入到指定csv文件中,参数 index=False不写入索引列
import pandas as pd
CSV_FILE_PATH = './test.csv'
df = pd.read_csv(CSV_FILE_PATH)
print(df.head(5))
Df1=df.head(10)
Df1.to_csv(‘top10.csv’)
(1)跳过文件中的几行数据之后再读取
df = pd.read_csv(CSV_FILE_PATH, skiprows=1)
(2)给数据指定列标题columns
df = pd.read_csv(CSV_FILE_PATH, names=[])
(3)读取指定列的数据
df = pd.read_csv(CSV_FILE_PATH,usecols=[0,1,2]) #指出读取文件的列号,从0开始
(4)读取指定行的数据
df = pd.read_csv(CSV_FILE_PATH,nrows=5]) #读取前五行