Some simple csv file read and write operations

1. Write the csv file

import csv

'''写入csv文件'''
# encoding:编码格式,  newline=""可让数据不用隔行写入
with open('demo.csv','w',encoding='utf-8',newline="",) as datacsv:
    csv_writer = csv.writer(datacsv, dialect=("excel"),)
    csv_writer.writerow(['A','B','C','D','E','F'])
    csv_writer.writerow(['1','2','3','4','5','6'])

result:
insert image description here

2. Reading of csv files

'''读csv文件'''

f = open('demo.csv', 'r')
reader = csv.reader(f)
# print(next(reader))  # 读取一行
# print(next(reader))  # 读取下一行

# for循环读取
for i in reader:
    print(i)

result:
insert image description here

3. Read and write files in the panda library (simpler)

'''pandas库读写操作'''

import pandas as pd
filename = 'demo.csv'
# 读文件
df = pd.read_csv(filename)
print(df)

# 取出df的前5行
data = df.head()
# 写入文件
data.to_csv('demo_01.csv')

result:
insert image description here
insert image description here

I found that there is a little more in the write operation of pandas: the comma in the first line and the 0 in the second line (if there is data below, there must be 1, 2, 3...), these are called index indexes, if you want To remove the index index in the csv file, just add a sentence of index=False when writing.

data.to_csv('demo_01.csv',index=False)

result:
insert image description here

Guess you like

Origin blog.csdn.net/qq_43750528/article/details/130408518