【问题标题】:How to move or copy a figure with .png extension from one folder to other folder? [duplicate]如何将扩展名为 .png 的图形从一个文件夹移动或复制到另一个文件夹? [复制]
【发布时间】:2020-01-04 04:14:36
【问题描述】:

我在 Dist 文件夹中保存了一个带有 .png 扩展名的图形。现在在一个 for 循环中,我想实现一个条件,如果 i

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    这里有两种方法可以将文件复制到另一个文件夹:

    例如,如果我们有这个树目录:

    .
    ├── destination  # destination directory
    ├── moving.py    # script that copies files
    └── test.png     # file to be copied
    

    moving.py:

    import os
    import shutil
    
    
    # Method 1
    def copy_file(filename: str, destination: str):
        """Copy file to destination using shutil package
           :param: filename is the file name path
           :param: destination is the destination path
        """
        shutil.copy(filename, destination)
    
    
    # Method 2
    def copy_file2(filename: str, destination: str):
        """Copy file to destination"""
        data = b''
        # Read the file in binary mode
        with open(filename, 'rb') as f:
            data = f.read()
        # Write the file in binary mode
        with open(os.path.join(destination, filename), 'wb') as f:
            f.write(data)
    
    
    # Example
    filename = 'test.png'
    destination = 'destination'
    copy_file(filename, destination)
    # copy_file2(filename, destination)
    

    这两种方法都会将文件复制到新的目标路径,并保留复制文件的原始名称。

    奖励:有关shutil.copy() 功能的更多信息,我建议您阅读official documentation

    【讨论】:

      猜你喜欢
      • 2011-08-22
      • 2020-07-30
      • 2018-09-28
      • 2015-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-14
      • 1970-01-01
      相关资源
      最近更新 更多