【问题标题】:How to copy files containing certain string using Shutil?如何使用 Shutil 复制包含特定字符串的文件?
【发布时间】:2019-06-28 23:21:34
【问题描述】:

我的任务是编写一个非常简单的脚本,但我终其一生都无法弄清楚如何...

我需要做的就是使用 Shutil 模块将所有包含“Tax_”的文件从 ~/Documents 文件夹复制到我当前的工作目录。

import shutil
import os

src = os.path.expanduser('~/Documents/Tax 2018')
dst = os.getcwd()

for files in src:
    if 'bdd' in files: # also tried: if files.startswith("Tax_")
        shutil.copy(files,dst)

不起作用。我们还可以选择使用Shutil.which("Tax_") 查找文件,但这根本不起作用。

【问题讨论】:

  • 文件内容,还是文件名?
  • 文件名@WillemVanOnsem

标签: python file copy shutil


【解决方案1】:

你可以试试这样的:

from glob import glob

for file in glob('~/Documents/Tax 2018/Tax_*'):
    shutil.copy(file, dst)

glob 将返回与通配符模式匹配的文件列表,在他的情况下,这些文件在给定路径上以 Tax_ 开头。

【讨论】:

    【解决方案2】:

    也许这样的东西对你有用。它会询问您输入目录,然后询问您要将文件保存在哪里。如果保存目录不存在,则创建它,如果保存目录已存在,则继续。最后的 input() 函数只是用来离开 python 控制台,这样你就可以看到它已经完成了。

    使用 shutil.copy2 的好处是它会尝试保留文件的元数据。

    另外,根据文件的命名方式,您可能不是很具体,您可能需要稍微更改这一行 if 'tax_' in file.lower():

    import shutil
    import os
    
    
    input_dir = input('Please enter directory that contains that tax files.\n')
    output_dir = input('\nPlease enter the path where you want to save the files.\n')
    
    
    for file in os.listdir(input_dir):
        if 'tax_' in file.lower():
    
            if not os.path.exists(output_dir):
                os.makedirs(output_dir)
    
            shutil.copy2(os.path.join(input_dir, file), os.path.join(output_dir, file))
    
    input('\nFinished --> Files are saved to %s' % output_dir)  # format() or f strings are ideal but not sure which python version you have
    

    【讨论】:

      【解决方案3】:

      确保为文件指定文件类型,希望这对您有用:

      #!/usr/bin/env python3
      
      #Imports
      from shutil import copyfile
      import shutil
      import os
      
      # Assigning the variables to search and the location
      file_str = "Tax_201"
      search_path = os.path.join(os.path.expanduser('~'),'Documents')
      
      # Repeat for each file in the search path
      for filename in os.listdir(path=search_path):
          # Check if the file starts with Tax_2018
          if filename.startswith(file_str):
              # Assigning the variables for the src and destination
              path_src = os.path.join(os.path.expanduser('~'),'Documents', filename)
              path_destination = os.path.join(os.path.expanduser('~'),'Documents', 'Taxes', filename)
              # Copy the file that matched the file_str
              shutil.copyfile(path_src, path_destination)
          else:
              # Stop the loop
              break
      

      输出

      文件/ ├── 税收 ├── Tax_2018.txt ├── Tax_2019.txt 文件/税收/ ├── Tax_2018.txt ├── Tax_2019.txt

      【讨论】:

      • 连接路径不是很好的做法,并且可能导致错误,尤其是在不同的操作系统上时。你应该让 python 用os.path.join() 为你做这件事
      【解决方案4】:

      请尝试:

      import glob
      import os
      import shutil
      
      dst = os.getcwd()
      str_target = 'bdd'     # OR 'Tax_'
      
      f_glob = "~/Documents/Tax 2018/{}*.txt".format(str_target)
      ls_f_dirs = glob.glob(f_glob)
      
      for f_dir in ls_f_dirs:
          shutil.copy(f_dir, dst)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-17
        • 1970-01-01
        • 2015-05-20
        • 2018-09-03
        • 1970-01-01
        • 2019-10-13
        • 1970-01-01
        • 2023-03-20
        相关资源
        最近更新 更多