import pandas as pd
import PySimpleGUI as sg
import os
from pathlib import Path
import csv
import datetime
#import re
def csv_xlsx_file(file_name):
end_name = os.path.splitext(file_name)[1]
if end_name == '.txt':
print(file_name)
elif end_name == '.csv':
reader1 = list(csv.reader(open(file_name, "rU", encoding='utf8', errors='ignore'), delimiter=','))
writer = csv.writer(open(file_name, 'w', newline='', encoding='utf8', errors='ignore'), delimiter='|')
writer.writerows(row for row in reader1)
elif end_name == '.xlsx':
new_csv_name = os.path.splitext(file_name)[0] + '.csv'
print(new_csv_name)
os.makedirs(os.path.dirname(new_csv_name), exist_ok=True)
# xlsx文件转换成csv内容
data = pd.read_excel(file_name, index_col=0) # index_col=0如果不设置,转换后csv文件第一列就会是索引0,1,2...
data.to_csv(new_csv_name, encoding='utf8')
# 读取内容写入新建的csv文件并替换分隔符
reader1 = list(csv.reader(open(new_csv_name, "rU", encoding='utf8', errors='ignore'), delimiter=','))
writer = csv.writer(open(new_csv_name, 'w', newline='', encoding='utf8', errors='ignore'), delimiter='|')
writer.writerows(row for row in reader1)
if __name__ == '__main__':
file_name = sg.popup_get_file("选择文件",multiple_files=True,font="宋体",text_color='black')
print(file_name)
start_date = datetime.datetime.now()
print(start_date)
lable_check = file_name.find(';')
if lable_check != -1:
singel_fname =file_name.split(';')
for file_name in singel_fname:
print(file_name)
csv_xlsx_file(file_name)
end_date = datetime.datetime.now()
print(end_date - start_date)
else:
csv_xlsx_file(file_name)
end_date = datetime.datetime.now()
print(end_date - start_date)
python xlsx转换csv 并自动创建csv文件且替换csv分隔符
于 2023-01-06 14:08:02 首次发布