python读写txt、csv文件
程序员文章站
2022-06-15 18:45:15
python 读写文件2、读写 txt 文件(1)读取 txt 文件(2)写入 txt 文件3、读写csv文件(1)读取 csv 文件# read_csvdata = pd.read_csv(r'D:\学习\python\file\excel\data.csv')# csvimport csvwith open(r'D:\学习\python\file\excel\data.csv', 'r',encoding='utf-8') as f: data = df(csv.rea...
python 读写txt、csv文件
1、读写 txt 文件
(1)读取 txt 文件
# read():读取全部 with open(r'D:\学习\python\file\txt\data1.txt', 'r', encoding = 'utf-8') as f: data1 = f.read() # readline(): 读取第一行内容 with open(r'D:\学习\python\file\txt\data1.txt', 'r', encoding = 'utf-8') as f: data1 = f.readline() # readlines(): 读取文本全部内容,返回列表 with open(r'D:\学习\python\file\txt\data1.txt', 'r', encoding = 'utf-8') as f: data1 = f.readlines() data1 = [s.strip('\n') for s in data1]
(2)写入 txt 文件
# 字符串导出txt with open(r'D:\学习\python\file\txt\data1.txt', 'w', encoding = 'utf-8') as f: f.write('good1!'+'\n'+'good2!') # DataFrame导出txt data.to_csv(r'D:\学习\python\file\txt\data.txt', encoding = 'utf-8')
2、读写csv文件
(1)读取 csv 文件
# read_csv data = pd.read_csv(r'D:\学习\python\file\excel\data.csv') # csv import csv with open(r'D:\学习\python\file\excel\data.csv', 'r',encoding='utf-8') as f: data = df(csv.reader(f))
(2)写入 csv 文件
# to_csv data.to_csv(r'D:\学习\python\file\excel\data.csv',index = None) # csv with open(r'D:\学习\python\file\excel\data.csv', 'w',encoding='utf-8') as f: wr = csv.writer(f) #先写入columns_name wr.writerow(list(data)) #写入多行用writerows for i in range(len(data)): wr.writerow(list(data.iloc[i,:]))
注:
1、open(‘file’,‘mode’):
file:路径
mode(可选):打开文件的模式,如只读、追加、写入等
r:表示文件只能读取,默认
w:表示文件只能写入
a:表示打开文件,在原有内容的基础上追加内容,在末尾写入
w+: 表示可以对文件进行读写双重操作
2、open 前最好加上 with,数据读写之后,会自动关闭文件
本文地址:https://blog.csdn.net/weixin_40012554/article/details/108802081
下一篇: 网络通信与服务器之网络-udp通讯方式