首页 > 解决方案 > 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

提前致谢

标签: pythonexcel

解决方案


检查这是否有效

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)

推荐阅读