今天在将已经爬取完存成txt文件批量导入保存csv格式时,文本中的汉字能够正常正常显示,但是用正常的方法保存到csv中就成了乱码。
最开始的写法:
with open(city+'.csv','a+') as csv_file:
csv_file.write(line)
打开文件发是乱码,于是又重新改写增加
encoding='utf-8')
满心欢喜的去看生成的文件,但是又一次的让我失望而归,后来没办法去网上到处找资料 ,终于让我找到了方法,就是将原来的
'utf-8' 换成 'utf-8-sig'
代码如下
with open(city+'.csv','a+',encoding='utf-8-sig') as csv_file:
csv_file.write(line)
这次果然成功了,不知道具体原因是什么,但是却实现了我想要的效果。
下面放出我写的简单的将当前目录下的所有txt文件转成 csv文件的代码,此代码会自动根据相应的文件夹名字保存csv文件的名称 并保存,写的不是很完善,有大佬看到的话,多多指教。
源码:
import csv
import os
root_path =os.path.dirname(os.path.abspath(__file__))+'\山东省'
# print(root_path)
city_list=os.listdir(root_path)
# print(city_list)
for city in city_list:
# print(city)
city_path=os.path.join(root_path,city)
# print(city_path)
for i in range(32):
file_path=city_path+r'\{}.txt'.format(str(i))
if not os.path.exists(file_path):
continue
else:
with open(file_path,'r',encoding='utf-8') as f_txt:
txt_lines=f_txt.readlines()
# print(txt_lines)
for line in txt_lines:
with open(city+'.csv','a+',encoding='utf-8-sig') as csv_file:
csv_file.write(line)
print('写入完成')
网友评论