我正在尝试将文件和文件夹从目录移动到另一个目录。我目前面临两个问题。
- 它似乎只移动文件,但不移动任何文件夹。
- 它仅选取大写或小写。
你知道这样做可能会缺少什么吗?我可以使用 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/