python csv文件读取写入 *** 作

python csv文件读取写入 *** 作,第1张

import csv

写入内容
newline=""   新的一行隔行去掉
encoding指定字符集编码的
with open("练习.csv","w",newline="",encoding="utf-8") as f:
    csvweiter = csv.writer(f,dialect=("excel"))#写入数据,dialect=("excel")可写可不写,默认就是excel
    csvweiter.writerow(['^','#','$','%'])#写入一行
    csvweiter.writerow(['A','B','C','D'])
    csvweiter.writerow(['1','2','3','4'])

读取文件
f = open("练习.csv","r")
reader = csv.reader(f)
print(next(reader))#读取一行
print(next(reader))
print(next(reader))
for i in reader:
    print(i)

#使用pandas读取或者写入
import pandas as pd
#pandas读取
filename = "练习.csv"
df = pd.read_csv(filename)
print(df.head(6))#df.head(n):读取前n行数据,默认读取前五行

#pandas写入
data = df.head()
data.to_csv('练习1.csv',index=False)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/715722.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-25
下一篇 2022-04-25

发表评论

登录后才能评论

评论列表(0条)

保存