【发布时间】:2015-12-24 15:48:46
【问题描述】:
有没有办法使用 Python 3 shutil 复制只读文件,使目标文件不接收源文件的只读模式?
我已成功使用 shutil 创建文件的工作副本:
import os, stat
inputfile = 'inputfile.json' # A read-only file
outputfile = 'outputfile.json' # A file I want to keep writeable
os.chmod(outputfile, stat.S_IWRITE) # If outputfile exists, ensure it's writeable
shutil.copy(inputfile, outputfile) # Rats! -- shutil included read-only attributes in copy operation
但是shutil 还复制了输入文件的只读属性以及文件内容。我不想那样。
显然我可以在复制操作后重复 os.chmod 命令。而且我知道如何在不使用 shutil 的情况下创建可写副本。但是是否可以使用 shutil 来复制文件的内容而不复制其属性(?)
【问题讨论】:
-
Ignacio Vazquez-Abrams 和 Saxony 的 Rolf 在下面给出的两个答案都有效: shutil.copyfileobj() 和 shutil.copyfile() 似乎都在复制文件内容,同时离开目标文件可写。不知道我之前做错了什么,这让我得出结论,他们将我的目标文件设置为只读...