【问题标题】:How to move file from folder A to folder B in python?如何在python中将文件从文件夹A移动到文件夹B?
【发布时间】:2021-10-17 11:44:27
【问题描述】:

我做错了什么 我需要改进什么?

import os
source = "C:\\Users\\User\\Desktop\\ala.txt"
destination = "C:\\Users\\User\\Desktop\\zzz.txt"

try:
    if os.path.exists(destination):
        print("There is already a file there")
    else:
        os.replace(source,destination)
        print(source+" was moved")
except FileNotFoundError:
    print(source+" was not found")

【问题讨论】:

  • 您遇到的实际问题是什么?您的代码按预期工作,是吗?

标签: python file line move catalog


【解决方案1】:

您可以尝试导入shutil并调用 shutil.move(源,目的地)。 shutil 模块提供了移动文件以及整个文件夹的功能。

【讨论】:

    【解决方案2】:

    你也可以像这样尝试使用 shutil 包:

    import os
    import shutil
    
    source = r"C:\Users\omkar\Desktop\source"
    destination = r"C:\Users\omkar\Desktop\destination"
    
    allfiles = os.listdir(source)
    
    for f in allfiles:
    
        shutil.move(source+ r"\\" + f, destination)
    

    【讨论】:

      猜你喜欢
      • 2011-07-22
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多