Python: 把txt文件转换成csv
最近在项目上需要批量把txt文件转成成csv文件格式,以前是手动打开excel文件,然后导入txt来生产csv文件,由于这已经变成每周需要做的事情,决定用python自动化脚本来实现,思路:
- 读取文件夹中所有txt文件,保存到list中
- 针对每个txt文件,自动生产同文件名的csv文件
- 对每个txt文件,根据分隔符来保存为csv文件,分隔符为分号“;”,在转换之前先把文件编码统一成'utf-8',因为在实现过程中,发现总会有编码报错问题出现
- 新建txt文件夹来存放所有txt文件
完整代码如下:
import csv
import os
import shutil
from chardet.universaldetector import UniversalDetector def get_encode_info(file):
with open(file, 'rb') as f:
detector = UniversalDetector()
for line in f.readlines():
detector.feed(line)
if detector.done:
break
detector.close()
return detector.result['encoding'] def read_file(file):
with open(file, 'rb') as f:
return f.read() def write_file(content, file):
with open(file, 'wb') as f:
f.write(content) def convert_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 *.txt to a folder
def move2txtfolder(path, txt_file_list):
txt_folder_path = path + '\\txt'
if not os.path.exists(txt_folder_path):
os.makedirs(txt_folder_path) for file in txt_file_list:
des_path = os.path.join(txt_folder_path, os.path.basename(file))
shutil.move(file, des_path) ##在路径中找出所有的*.txt文件
def findtxt(path, txt_file_list):
file_name_list = os.listdir(path)
for filename in file_name_list:
de_path = os.path.join(path, filename)
if os.path.isfile(de_path):
if de_path.endswith(".txt"): # Specify to find the txt file.
txt_file_list.append(de_path)
else:
findtxt(de_path, txt_file_list) def txt2csv(txt_file):
##先把所有文件的encoding都转换成utf-8
encode_info = get_encode_info(txt_file)
if encode_info != 'utf-8':
convert_encode2utf8(txt_file, encode_info, 'utf-8') csv_file = os.path.splitext(txt_file)[0] + '.csv'
with open(csv_file, 'w+', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile, dialect='excel') with open(txt_file, 'r', encoding='utf-8') as txtfile:
for line in txtfile.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) for file in os.listdir(folder_path) if os.path.join(folder_path, file).endswith('.txt')] for txt_file in txt_file_list:
txt2csv(txt_file) move2txtfolder(folder_path, txt_file_list)
Python: 把txt文件转换成csv的更多相关文章
- csv 如何将txt文件转换成csv文件
import csvdef convert_txt_to_csv(out_file_path, input_file_path, txt_sep): #定义输出路径,输入文件路径,txt的分隔符 wi ...
- 将文本(lrc,txt)文件转换成UTF-8格式
UTF-8是UNICODE的一种变长字符编码又称万国码,由Ken Thompson于1992年创建.现在已经标准化为RFC 3629.UTF-8用1到6个字节编码UNICODE字符.用在网页上可以同一 ...
- TXT文件转换成DataSet数据集
/// <summary> /// TXT文件转换成DataSet数据集 /// </summary> /// <param name="FilePath&qu ...
- 用Python将word文件转换成html(转)
用Python将word文件转换成html 序 最近公司一个客户大大购买了一堆医疗健康方面的科普文章,希望能放到我们正在开发的健康档案管理软件上.客户大大说,要智能推送!要掌握节奏!要深度学习!要 ...
- 通过python将xml文件转换成html文件
#数据类型的转换 def main(): maxwidth = 100 #用于规范字段的长度 print_start() count=0 while True: ...
- 将txt文件转换成EXCEL文件的方法
地址:http://wenku.baidu.com/view/fcdbe8cca1c7aa00b52acbad.html 1.在EXCEL程序中点击“打开”,将文件类型选择为“文本文件”,找到以前用过 ...
- python 把txt文件分隔成0.8和0.2的比例的新文件
from math import sqrt import randomimport osfrom sklearn import cross_validation os.chdir("/*&q ...
- 将DataTable转换成CSV文件
DataTable用于在.net项目中,用于缓存数据,DataTable表示内存中数据的一个表.CSV文件最早用在简单的数据库里,由于其格式简单,并具备很强的开放性,所以起初被扫图家用作自己图集的标记 ...
- 转换成CSV文件、Word、Excel、PDF等的方法--读取CSV文件的方法
1. 转换成CSV文件: http://www.dotnetgallery.com/lab/resource93-Export-to-CSV-file-from-Data-Table-in-Aspne ...
随机推荐
- 如何防止XSS攻击?
来自: https://www.freebuf.com/articles/web/185654.html 前端安全 随着互联网的高速发展,信息安全问题已经成为企业最为关注的焦点之一,而前端又是引发企业 ...
- 201871010136-赵艳强《面向对象程序设计(Java)》第八周学习总结
201871010136-赵艳强<面向对象程序设计(Java)>第八周学习总结 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这 ...
- selenium 定位 页面上两个完全一样的元素
在测试过程中发现页面上有两个保存按钮的元素的xpath一模一样,如下图: google了好久才找到解决办法,发现自己还是比较弱!!!解决方法如下: selenium.click("xpath ...
- Docker常用安装(九)
一.安装mysql 1. docker hub上面查找mysql镜像 2. 拉取镜像 #获取mysql镜像 docker pull mysql:5.6 3. 运行容器 docker run -p 1 ...
- python异步编程
python用asyncio 模块实现异步编程,该模块最大特点就是,只存在一个线程 由于只有一个线程,就不可能多个任务同时运行.asyncio 是"多任务合作"模式(coopera ...
- [RN] React Native 错误 Module does not exist in the module map
React Native 错误 Module does not exist in the module map 代码如下: import Login from 'login' import Index ...
- Codeforces Round #576 (Div. 1)
Preface 闲来无事打打CF,就近找了场Div1打打 这场感觉偏简单,比赛时艹穿的人都不少,也没有3000+的题 两三个小时就搞完了吧(F用随机水过去了) A. MP3 题意不好理解,没用翻译看了 ...
- [LeetCode] 315. Count of Smaller Numbers After Self 计算后面较小数字的个数
You are given an integer array nums and you have to return a new counts array. The countsarray has t ...
- [LeetCode] 148. Sort List 链表排序
Sort a linked list in O(n log n) time using constant space complexity. Example 1: Input: 4->2-> ...
- Windows的一些使用技巧/设置
仅为个人记录,关闭与否还请读者斟酌 1,加速关机速度 运行gpedit.msc: 计算机管理,管理模块 - 系统 -关机选项 关闭会阻止或取消关机的应用程序的自动终止功能. 2,组策略关闭小娜后,只把 ...