python uses pandas to convert excel files to txt files
- 2020-12-22 17:44:26
- OfStack
There are many ways for python to swap data for txt, and you can do so using the xlrd library. I am lazy and do not want to use too many plug-ins, using the existing library pandas to convert excel files to txt files.
Direct code:
'''
function Will: excel File conversion to text
author : Nstock
date : 2018/3/1
'''
import pandas as pd
import re
import codecs
# will excel into txt file
def exceltotxt(excel_dir, txt_dir):
with codecs.open(txt_dir, 'w', 'utf-8') as f:
neg=pd.read_excel(excel_dir, header=None, index=None)
f.write(neg.to_string())
# Removes the number and space at the beginning of the record line
def del_linehead_number_speace(orig_txt_dir,saveas_txt_dir):
with open(orig_txt_dir,'r+') as f, open(saveas_txt_dir,'r+') as fw:
lines = f.readlines()
print(len(lines)) # The number of rows
texts = [re.sub(r'(\d)+(\s)+','',lines[num]) for num in range(len(lines)) ]
texts = list(set(texts)) # De-duplication this line if you want to keep duplicate notes
line_num = len(texts)
# for num in range(line_num): # View the converted text
# print(texts[num])
fw.writelines(texts)
exceltotxt('./data/neg.xls', './data/neg_temp.txt')
del_linehead_number_speace('./data/neg_temp.txt','./data/neg.txt')
xxx_dir with target file name: xxx_dir=' save path /'+' file name '