2017-04-03 158 views
0

我想在源路径中仅移动“.hex”扩展名的文件。我写下如下的代码;在Python 3中仅移动“.hex”扩展名的文件

os.makedirs(dst) 
src = "C:\\source_path" 
dst = "C:\\destination_path" 

for filename in os.listdir(): 
    if filename.endswith('.hex'): 
     shutil.move(src, dst , copy_function = copy2) 

该文件已创建但为空。

+0

的可能的复制[使用python的水珠从目录列表文件(http://stackoverflow.com/questions/22625616/listing-files-from-a-directory-using-glob-python) –

+0

为什么使用'copy_function = copy2'? 尝试使用 'os.rename(src,dst)' 'shutil.move(src,dst)' – Surajano

+1

您需要指定文件路径而不仅仅是dir名称。 – bernie

回答

0
  1. 你需要移动文件,而不是文件夹。 (使用os.path.join(src,filename)
  2. 你不会超过src dir。 (使用os.listdir(src)

尝试是这样的:

os.makedirs(dst) 
src = "C:\\source_path" 
dst = "C:\\destination_path" 

for filename in os.listdir(src): 
    if filename.endswith('.hex'): 
     shutil.move(os.path.join(src,filename), dst) 
0
src = "C:\\source_path" 
dst = "C:\\destination_path" 
os.makedirs(dst, exist_ok=True) 

第一种方式;

source = os.listdir(src) 
for files in source: 
    if files.endswith(".hex"): 
     if not files.endswith("sample.hex"): 
      shutil.move(files,dst) 

第二种方法;

source = os.listdir(src) 
for files in source: 
    if files.endswith(".hex"): 
     if not files.endswith("sample.hex"): 
      shutil.move(os.path.join(src, files), os.path.join(dst, files))