当前位置:   article > 正文

python写入与读取txt、tsv、csv、excel等文件_pd.写txt

pd.写txt

1.1读取txt

vocabs=[]

with open(“D:/vocab_init.txt”, “r”) as f:
for line in f.readlines():
line = line.strip(‘\n’) #去掉列表中每一个元素的换行符
#print(line)
vocabs.append(line)

1.2 写入txt

final_vocabs = [‘1’,‘2’]
file = open(‘D:/vocab.txt’, ‘w’)
for i in range(len(final_vocabs)):
s = str(final_vocabs[i])+ ‘\n’
file.write(s)
file.close()

1.3 pd 读取csv

import pandas as pd
import csv
train_file=‘D:/train.csv’
traindata=pd.read_csv(train_file)

2.1 pd读取tsv

import pandas as pd
import csv
train_file=‘D:/28.tsv’
traindata=pd.read_csv(train_file, sep=‘\t’,header=None)

2.2 pd写入tsv

import pandas as pd
import csv
final_result= [1,2]
result = pd.DataFrame(final_result)
result.to_csv(‘D:/28.tsv’, sep=‘\t’, index=False, header=False, quoting=csv.QUOTE_NONE)

2.3 pd读取excel

train_file=“D:/tianchi .xlsx”
traindata=pd.read_excel(io=train_file)

2.3.1 读取excel sheet

datas = pd.read_excel(io=train_file,sheet_name=‘开放信息’)

3.1 关于UnicodeDecodeError: ‘gbk’ codec can’t decode byte的解决办法

将with open(file) as f: 改成 with open(file, ‘r’, encoding=‘utf-8’) as f:

3.2 Excel xlsx file; not supported

原因是最近xlrd更新到了2.0.1版本,只支持.xls文件。所以pandas.read_excel(‘xxx.xlsx’)会报错。

可以安装旧版xlrd,在cmd中运行:

pip uninstall xlrd
pip install xlrd==1.2.0

也可以用openpyxl代替xlrd打开.xlsx文件:

df=pandas.read_excel(‘data.xlsx’,engine=‘openpyxl’)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/596072
推荐阅读
相关标签
  

闽ICP备14008679号