python - Python:收集所有 xlsx。- 打开 - 添加列 - 保存在新文件夹中
问题描述
我是 Python 新手,但试图编写一个代码,在多个 .xlsx 文件上添加一列,并将这些文件与原始名称一起保存到一个新文件夹中。
我从下面的一些编码开始,但在打开所有文件并保存到我的DestPath
. 如果有人对此有解决方案会很高兴:
from os import listdir, path
import pandas as pd
import xlrd
SourcePath = 'C:\' #Source Path
DestPath = 'C:\' #Destination Path
# Listing up all .xlsx files from Source
def find_xlsx_filenames( path_to_dir, suffix=".xlsx" ):
filenames = listdir(path_to_dir)
return [ filename for filename in filenames if filename.endswith( suffix ) ]
filenames = find_xlsx_filenames(SourcePath)
fname = path.join(SourcePath, filenames[0]) # Tar første fil i mappa.
outname = path.join(outputdata, filenames[0])
for i in range(len(filenames)):
fname = path.join(SourcePath, filenames[i])
df = pd.read_excel(fname) #Read Excel file as a DataFrame
df['new_col'] = 'Sort Data' #Adding a new column named <Sort Data>
#To save it back as Excel
df.to_excel(DestPath, outname) #Write DateFrame back as Excel file
提前致谢
解决方案
检查这是否有效
import os
import pandas as pd
path = 'C:/'
for roots, dirs, files in os.walk(path):
xlsfile = [ _ for _ in files if _.endswith('.xlsx')]
for xlsf in xlsfile:
df = pd.read_excel(os.path.join(roots, xlsf))
df['Sort Data'] = ' '
df.to_excel(os.path.join(roots, xlsf), index = False)
推荐阅读
- android - Android Studio 3.6.3 未在 XML 中显示建议
- php - 在处理数千条记录时防止 php 脚本超时
- c++ - Arduino/C++ 在循环中调整 Long Millis ()
- c++ - 禁用 Visual Studio 自动完成
- sql - 如何使用 AND 和 OR 运算符简化 SQL 查询以检索特定列的总和?
- git - git reset --keep HEAD 什么都不做吗?
- java - indexOf的递归实现
- google-sheets - 如何在 Google 表格函数中使用当前单元格中的值?
- sql - 动态生成最近 36 个月的日期
- sql - 在 Hibernate 中插入多行