python - 尝试通过Python移动文件但无法移动文件夹

标签 python

我正在尝试将文件和文件夹从目录移动到另一个目录。我目前面临两个问题。

  1. 它似乎只移动文件,但不移动任何文件夹。
  2. 它仅选取大写或小写。

你知道这样做可能会缺少什么吗?我可以使用 startswith 添加 or 语句,但想看看是否有更好的方法来做到这一点。

import os
from os import path
import shutil

src = "C:/Users/test/documents/"
dst = "C:/Users/test/Documents/test"

files = [i for i in os.listdir(src) if i.startswith("C") and \
         path.isfile(path.join(src, i))]
for f in files:
    shutil.move(path.join(src, f), dst)

最佳答案

这将遍历源目录,创建目标目录中尚不存在的任何目录,并将文件从源目录移动到目标目录:

(据我了解,这就是你想要的)

import os
import shutil

src = "C:/Users/test/documents/"
dst = "C:/Users/test/documents/test"

for src_dir, dirs, files in os.walk(src):
    dst_dir = src_dir.replace(src, dst, 1)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            os.remove(dst_file)
        shutil.move(src_file, dst_dir)

关于python - 尝试通过Python移动文件但无法移动文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58913359/

相关文章:

Python Bigram 字典格式

android - 使用 Arduino 和 pySerial 进行串行数据记录

python - 如何在新文件名中复制带有日期的图像?

python - 以空字典作为值将 JSON 文件加载到 BigQuery

java - 如何在Pycharm/Eclipse中分别查看Python/Java的内部代码实现?

python - pandas - 如何过滤 "most frequent"日期时间对象

python - 如何使用枚举键将用户输入添加到字典中?

python - 使用 BlueZ 5 模拟键盘

python - 如何在 python 中通过 jsonschema 过滤 json

python - Python中的特定子矩阵提取