csv转xlsx
import os
import pandas as pd
path = "绝对路径"
for root, dirs, files in os.walk(path):
"""
应该是位置传参.
root 为 path的路径.
dirs 为 path路径下的所有目录.
files 为 dirs目录下所有存在的文件
"""
for item in files:
if item.endswith(".csv"):
file_dir = os.path.join(root, item)
try:
csv_file = pd.read_csv(file_dir, low_memory=False, encoding='utf-8')
del_lines = csv_file.drop_duplicates()
xlsx_file_name = file_dir.replace(".csv", ".xlsx")
if not os.path.exists(xlsx_file_name):
del_lines.to_excel(xlsx_file_name, index=False, encoding='gbk')
if os.path.exists(xlsx_file_name):
print(xlsx_file_name, "完成")
except Exception as e:
print(file_dir, ValueError(e))
pass
xlsx转csv
注意: pip install xlrd==1.2.0 这个一定要安装低版本的.
import os
import pandas as pd
path = "绝对路径"
for root, dirs, files in os.walk(path):
"""
应该是位置传参.
root 为 path的路径.
dirs 为 path路径下的所有目录.
files 为 dirs目录下所有存在的文件
"""
for item in files:
if item.endswith(".xlsx"):
file_dir = os.path.join(root, item)
try:
excel_file = pd.read_excel(file_dir)
del_lines = excel_file.drop_duplicates()
csv_file_name = file_dir.replace(".xlsx", ".csv")
if not os.path.exists(csv_file_name):
del_lines.to_csv(csv_file_name, index=False, encoding='gbk')
if os.path.exists(csv_file_name):
print(csv_file_name, "完成")
except Exception as e:
print(file_dir, ValueError(e))
pass