[英]Attempting to move Files but unable to move Folders via Python
I am trying to move files and folders from directory to another.我正在尝试将文件和文件夹从目录移动到另一个目录。 I am currently facing two issues.我目前面临两个问题。
Do you know what might be missing to do this.你知道这样做可能会缺少什么吗? I could add an or
statement statement with startswith
but would like to see if there is a better way to do this.我可以使用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)
This will go through the source directory, create any directories that do not yet exist in the destination directory, and move the files from the source to the destination directory:这将 go 通过源目录,创建目标目录中尚不存在的任何目录,并将文件从源目录移动到目标目录:
(As I understand it, this is what you want) (据我了解,这就是你想要的)
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.