本文主要是介绍python實現excel轉txt代碼,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
python實現excel轉txt代碼
excel_to_txt.py
from datetime import datetime, timedelta
import os
import pytz
import pandas as pddef excel_to_txt(name, date):# Read Excel file into a DataFrame# df = pd.read_excel(f'/opt/module/data/excel/{name}.xlsx', header=None,skiprows=1)# df = pd.read_excel(f'hdfs://mycluster:8020/origin_data/hr_cn/db/is_gs_recruitment_data_full/excel/{name}.xlsx', header=None,skiprows=1)df = pd.read_excel(f'C:/Users/SARAH.X/PycharmProjects/pythonProject/data/excel/{name}.xlsx', header=None, skiprows=1)# Define output directory and path# output_directory = os.path.join('/opt/module/data', 'txt', date)output_directory = os.path.join('C:/Users/SARAH.X/PycharmProjects/pythonProject/data/', 'txt', date)os.makedirs(output_directory, exist_ok=True) # Create directory if it doesn't existoutput_path = os.path.join(output_directory, f'{name}.txt')# Check if the file already exists, if so, remove itif os.path.exists(output_path):os.remove(output_path)print(f'Existing file {output_path} removed.')# Write DataFrame to a new text fileprint('开始写入txt文件')df.to_csv(output_path, header=None, sep='\t', index=False)print('文件写入成功!')return output_pathif __name__ == '__main__':current_time = datetime.now(pytz.timezone('Asia/Shanghai'))one_day_ago = (current_time - timedelta(days=1)).strftime('%Y-%m-%d')local_file_path = excel_to_txt('example4', one_day_ago)print(local_file_path)
这篇关于python實現excel轉txt代碼的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!