csv转换为csv utf-8
将csv格式文件批量转换为csv utf-8格式文件,以下为使用Python处理的代码:
import os
import pandas as pd
# 存有文件的路径
current_path = os.getcwd()
# current_path = os.path.dirname('G:/weather_output2')
# 转换之后存放的路径为“UTF8”,会检查当前路径是否有,没有就创建
utf8_path = os.path.join(current_path, 'UTF8')
if not os.path.exists(utf8_path):
os.makedirs(utf8_path)
for file_name in os.listdir(current_path):
# 转换csv文件
if file_name.endswith('.csv'):
df = pd.read_csv(file_name,encoding='utf-8',low_memory=False)
# df = pd.read_csv(file_name, encoding='gbk', low_memory=False)
utf8_file_dir = os.path.join(utf8_path, file_name)
df.to_csv(utf8_file_dir.replace('.csv', 'utf8.csv'), encoding='utf-8-sig', index=False)
print('csv文件"{}"成功转换为csv格式'.format(file_name))
xlsx转为csv
批量转xlsx为csv文件,以下为使用Python处理的代码:
'''
程序用来将excel批量转换为csv文件, 指定源路径和目标路径
在main函数中指定源文件路径source, 目标文件路径ob
这个程序假设Excel文件放在:G:\..., 输出csv文件到:G:\cc
'''
import pandas as pd
import os
# 建立单个文件的excel转换成csv函数,file是excel文件名,to_file 是csv文件名
def excel_to_csv(file, to_file):
data_xls = pd.read_excel(file, sheet_name=0)
data_xls.to_csv(to_file, encoding='utf_8_sig')
# 读取一个目录里面的所有文件:
def read_path(path):
dirs = os.listdir(path)
return dirs
# 主函数
def main():
source = "G:\\weather_station\\2021-06-27" # 源文件路径
ob = "G:\\weather_station\\2021-06-27" # 目标文件路径
file_list = [source + '\\' + i for i in read_path(source)] # 将源文件路径里面的文件转换成列表file_list
j = 1
# 建立循环对于每个文件调用excel_to_csv()
for it in file_list:
# 给目标文件新建一些名字列表
j_mid = str(j)
j_csv = ob + '\\' + j_mid + ".csv"
excel_to_csv(it, j_csv)
print(it)
j = j + 1
if __name__ == '__main__':
main()