我有几个文件夹中的几个文件,如下所示:
dir
├── 0
│ ├── 103425.xml
│ ├── 105340.xml
│ ├── 109454.xml
│
│── 1247
│ └── doc.xml
├── 14568
│ └── doc.xml
├── 1659
│ └── doc.xml
├── 10450
│ └── doc.xml
├── 10351
│ └── doc.xml
如何将所有文档提取到单个文件夹中,并 for each 移动的文档添加文件夹名称:
new_dir
├── 0_103425.xml
├── 0_105340.xml
├── 0_109454.xml
├── 1247_doc.xml
├── 14568_doc.xml
├── 1659_doc.xml
├── 10450_doc.xml
├── 10351_doc.xml
我试图用以下方法提取它们:
import os
for path, subdirs, files in os.walk('../dir/'):
for name in files:
print(os.path.join(path, name))
UPDATE
此外,我还试图:
import os, shutil
from glob import glob
files = []
start_dir = os.getcwd()
pattern = "*.xml"
for dir,_,_ in os.walk('../dir/'):
files.extend(glob(os.path.join(dir,pattern)))
for f in files:
print(f)
shutil.move(f, '../dir/')
上面给出了每个文件的路径.但是,我不明白如何重命名和移动它们:
---------------------------------------------------------------------------
Error Traceback (most recent call last)
<ipython-input-50-229e4256f1f3> in <module>()
10 for f in files:
11 print(f)
---> 12 shutil.move(f, '../dir/')
/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/shutil.py in move(src, dst, copy_function)
540 real_dst = os.path.join(dst, _basename(src))
541 if os.path.exists(real_dst):
--> 542 raise Error("Destination path '%s' already exists" % real_dst)
543 try:
544 os.rename(src, real_dst)
Error: Destination path '../data/230948.xml' already exists
上面的错误说明了我为什么要用文件夹重命名它.