【问题标题】:Move files with only ".hex" extensions in Python 3在 Python 3 中移动仅具有“.hex”扩展名的文件
【发布时间】:2017-04-03 06:22:00
【问题描述】:

我想移动源路径中只有“.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)

文件已创建但为空。

【问题讨论】:

  • 为什么要使用copy_function = copy2 ??尝试使用os.rename(src, dst)shutil.move(src, dst)
  • 您需要指定文件路径而不仅仅是目录名。
  • 即使我写shutil.move(src, dst),目标文件也没有变化。我只是试试copy_function = copy2
  • 文件不断更新。没有固定的文件名。这就是为什么我尝试移动以 '.hex' 结尾的文件

标签: python python-3.x path move shutil


【解决方案1】:
  1. 您需要移动文件,而不是文件夹。 (使用os.path.join(src,filename)
  2. 您不会访问src 目录。 (使用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)

【讨论】:

    【解决方案2】:
    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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多