gpt4 book ai didi

python - shutil 移动文件保持相同的目录结构

转载 作者:太空狗 更新时间:2023-10-30 00:57:42 28 4
gpt4 key购买 nike

我想移动很多文件。这些文件的路径存储在列表中。我想保留整个目录结构,但想将它们移动到不同的文件夹。

例如文件是D:\test\test1\test1.txtD:\test\test1\test2.txt

我想将它们从 D:\移动到 C:\并保持目录结构。我应该怎么做?

这是我的代码,它不起作用

import os, fnmatch
import shutil


f=open('test_logs.txt','r') #logs where filenames are stored with filenames as first entry

for line in f:
filename=line.split()
output_file="C:" + filename[0].lstrip("D:")
shutil.move(filename[0],output_file)

我可以很好地读取文件名,并且可以很好地生成目标文件名,但是当我运行它时,它会给我一个错误提示“没有这样的文件或目录”(并给出输出文件名的路径)。

最佳答案

我想你想要这样的东西:

import sys
import os
import shutil

# terminology:
# path = full path to a file, i.e. directory + file name
# directory = directory, possibly starting with a drive
# file name = the last component of the path

sourcedrive = 'D:'
destdrive = 'C:'

log_list_file = open('test_logs.txt', 'r')
for line in log_list_file:
sourcepath = line.split()[0] # XXX is this correct?
if sourcepath.startswith(sourcedrive):
destpath = sourcepath.replace(sourcedrive, destdrive, 1)
else:
print >>sys.stderr, 'Skipping %s: Not on %s' % (sourcepath, sourcedrive)
continue

destdir = os.path.dirname(destpath)

if not os.path.isdir(destdir):
try:
os.makedirs(destdir)
except (OSError, IOError, Error) as e:
print >>sys.stderr, 'Error making %s: %s' % (destdir, e)
continue

try:
shutil.move(sourcepath, destpath)
except (OSError, IOError, Error) as e:
print >>sys.stderr, 'Error moving %s to %s: %s' % (sourcepath, destpath, e)

如果源目录是空的,你是否也想删除它?

关于python - shutil 移动文件保持相同的目录结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5533517/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com