【发布时间】:2019-01-24 12:30:57
【问题描述】:
我有一个文件夹和子文件夹结构如下:
D:/src
├─ xyz.xlsx
├─ dist
│ ├─ xyz.xlsx
│ ├─ xxx.zip
│ └─ xxy.xlsx
├─ lib
│ ├─ xy.rar
│ └─ xyx.xlsx
├─ test
│ ├─ xyy.xlsx
│ ├─ x.xls
│ └─ xyz.xlsx
我想从源目录和子目录中提取所有 excel 文件(xls 或 xlsx),根据 excel 文件名删除重复文件并将所有唯一文件放在 D:/dst 目录中。如何在 Python 中获得以下结果?谢谢。 预期结果:
D:/dst
├─ xyz.xlsx
├─ xxy.xlsx
├─ xyx.xlsx
├─ xyy.xlsx
├─ x.xls
这是我尝试过的:
import os
for root, dirs, files in os.walk(src, topdown=False):
for file in files:
if file.endswith('.xlsx') or file.endswith('.xls'):
#print(os.path.join(root, file))
try:
df0 = pd.read_excel(os.path.join(root, file))
#print(df0)
except:
continue
df1 = pd.DataFrame(columns = [columns_selected])
df1 = df1.append(df0, ignore_index = True)
print(df1)
df1.to_excel('test.xlsx', index = False)
【问题讨论】:
-
我认为您可以通过
shutil.copytree()完成所有这些工作。见问题Copying specific files to a new folder, while maintaining the original subdirectory tree。 -
@ahbon,解决这个问题还有什么不幸的吗?
-
感谢您的提问。我明天试试,如果有问题我会告诉你的。
-
@martineau 您提到的解决方案将所有 xlsx 和 xls 文件复制到新文件夹 D:/dst,但它保留原始子目录。如果我只想将它们放在一个文件夹中而忽略其原始子目录怎么办?
-
虽然您添加的所有 pandas 数据框内容都让人分心,并且与您的问题并不完全相关,但它暴露了——我认为——所谓的 XY Problem,因为它揭示了 为什么 你想要做这个文件复制。如果我理解正确,那么确实没有必要先将所有文件复制到一个文件夹中——只需使用找到它们的过程来复制它们,而不是驱动你想要做的它们的连接。这将大大减少需要完成的 I/O。