python - 文件夹被解释为文件

标签 python python-2.7 directory document shutil

我正在尝试从现有文件夹复制一个 word 文件并将其复制到新的输出文件夹。在此输出文件夹中,我再次根据用户 ID 创建了不同的文件夹,并且应在其中为每个用户放置 word 文件。但是,在复制此文件时,我遇到了一个问题,因为 id 文件夹被解释为 一份文件。输出文件图片附在这里:

the output file picture is attached here

我为此使用了 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/

相关文章:

templates - 如何使用 meteor 模板创建类似目录的结构?

python - 在 Python 中实现自动计数器的建议

python - 导入类实例化

python - 将每 3 行连接在一起 Python

python - Python 中匹配非空格的正则表达式

jquery - 获取给定目录中的文件名 jQuery

python - 类型错误 : only integer scalar arrays can be converted to scalar index while converting dataframe "to_datetime"

python - Visual Studio Code Intellisense 非常慢 - 我能做些什么吗?

python - 如何在子类中添加实例属性?

c++ - 获取两个目录之间的路径 "difference"