我正在尝试从现有文件夹复制一个 word 文件并将其复制到新的输出文件夹。在此输出文件夹中,我再次根据用户 ID 创建了不同的文件夹,并且应在其中为每个用户放置 word 文件。但是,在复制此文件时,我遇到了一个问题,因为 id 文件夹被解释为 一份文件。输出文件图片附在这里:
我为此使用了 shutil
模块,我编写的代码是:
id = tup2[i]
shutil.copy('C:\\Python27\\mydoc.docx', ('C:\\Python27\\Output\\%s') %(id))
最佳答案
这是预期的。如果目标文件夹存在,则 copy
附加文件的基本名称并将文件复制到目标文件夹中。
Copies the file src to the file or directory dst. src and dst should be strings. If dst specifies a directory, the file will be copied into dst using the base filename from src.
如果没有,则 copy
假定您想要复制并更改名称(unix cp
命令完全符合相同)。
解决方法是预先创建目录/确保它在此处:
import os,shutil
output_dir = os.path.join(r'C:\Python27\Output',str(id))
if not os.path.isdir(output_dir):
os.mkdir(output_dir)
shutil.copy(r'C:\Python27\mydoc.docx', output_dir)
(最好使用 os.path
中的适当路径处理函数和垃圾窗口路径的原始字符串)
关于python - 文件夹被解释为文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51283862/