Python:收集所有xlsx。 - 打开 - 添加列 - 保存在新文件夹中

时间:2018-04-26 08:33:06

标签: python excel

我是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

先谢谢

1 个答案:

答案 0 :(得分:0)

检查是否有效

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)