txt文件转为csv文件转化代码:
import csv# 输入txt文件路径txt_file = r'C:\Users\ZARD\Desktop\daily-min-temperatures.txt'# 输出csv文件路径csv_file = r'C:\Users\ZARD\Desktop\daily-min-temperatures.csv'# 打开txt文件以读取数据with open(txt_file, 'r') as txtfile:# 创建CSV写入器csv_writer = csv.writer(open(csv_file, 'w', newline=''))# 逐行读取txt文件,写入CSV文件for line in txtfile:# 删除末尾的换行符,并使用逗号分隔数据data = line.strip().split(',')csv_writer.writerow(data)print(f"{txt_file} 已成功转换为 {csv_file}")
csv文件转为xls文件:
# 读取xls文件xls_file = r'D:\Code_python\time series prediction\空气质量\pm25_data.xls'df = pd.read_excel(xls_file)# 将数据保存为csv文件csv_file = r'D:\Code_python\time series prediction\空气质量\pm25_data.csv'df.to_csv(csv_file, index=False)print(f"{xls_file} 已成功转换为 {csv_file}")