300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python把csv文件转换txt_Python实现txt文件转csv格式

python把csv文件转换txt_Python实现txt文件转csv格式

时间:2022-01-20 12:38:25

相关推荐

python把csv文件转换txt_Python实现txt文件转csv格式

码农公社 210= 102410月24日一个重要的节日--码农(程序员)节

把txt文件转成成csv文件格式,通过手动打开excel文件,然后导入txt来生产csv文件。

现在每周有大量的数据要处理,手动方式太不现实,决定用python自动化脚本来实现,思路:

1.读取文件夹中所有txt文件,保存到list中

2.对每个txt文件,自动生成同名的csv文件

3.对每个txt文件,根据分隔符来保存为csv文件,分隔符为分号“;”

在转换之前先把文件编码统一成'utf-8',因为在实现过程中,发现总会有编码报错问题出现。

4.新建txt文件夹来存放所有txt文件

完整代码如下:

importcsv

importos

importshutil

fromchardet.universaldetectorimportUniversalDetector

defget_encode_info(file):

withopen(file,'rb')asf:

detector=UniversalDetector()

forlineinf.readlines():

detector.feed(line)

ifdetector.done:

break

detector.close()

returndetector.result['encoding']

defread_file(file):

withopen(file,'rb')asf:

returnf.read()

defwrite_file(content,file):

withopen(file,'wb')asf:

f.write(content)

defconvert_encode2utf8(file,original_encode,des_encode):

file_content=read_file(file)

file_decode=file_content.decode(original_encode,'ignore')

file_encode=file_decode.encode(des_encode)

write_file(file_encode,file)

##Move*.txttoafolder

defmove2txtfolder(path,txt_file_list):

txt_folder_path=path+'\\txt'

ifnotos.path.exists(txt_folder_path):

os.makedirs(txt_folder_path)

forfileintxt_file_list:

des_path=os.path.join(txt_folder_path,os.path.basename(file))

shutil.move(file,des_path)

##在路径中找出所有的*.txt文件

deffindtxt(path,txt_file_list):

file_name_list=os.listdir(path)

forfilenameinfile_name_list:

de_path=os.path.join(path,filename)

ifos.path.isfile(de_path):

ifde_path.endswith(".txt"):#Specifytofindthetxtfile.

txt_file_list.append(de_path)

else:

findtxt(de_path,txt_file_list)

deftxt2csv(txt_file):

##先把所有文件的encoding都转换成utf-8

encode_info=get_encode_info(txt_file)

ifencode_info!='utf-8':

convert_encode2utf8(txt_file,encode_info,'utf-8')

csv_file=os.path.splitext(txt_file)[0]+'.csv'

withopen(csv_file,'w+',newline='',encoding='utf-8')ascsvfile:

writer=csv.writer(csvfile,dialect='excel')

withopen(txt_file,'r',encoding='utf-8')astxtfile:

forlineintxtfile.readlines():

line_list=line.strip('\n').split(';')

writer.writerow(line_list)

if__name__=='__main__':

folder_path=r'C:\Details'

###如果文件夹中还有子文件夹,请用findtxt函数

#txt_file_list=[]

#findtxt(folder_path,txt_file_list)

##如果文件夹中没有子文件夹的时候直接使用推导式来生产txt文件的list

txt_file_list=[os.path.join(folder_path,file)forfileinos.listdir(folder_path)ifos.path.join(folder_path,file).endswith('.txt')]

fortxt_fileintxt_file_list:

txt2csv(txt_file)

move2txtfolder(folder_path,txt_file_list)

引自/danvy/p/11667763.html,轻度整理。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。