2015-09-27 48 views
0

有没有办法使用Python 3 shutil复制一个只读文件,以便目标文件不会收到源文件的只读模式?使用Python 3 shutil来复制文件并保持destfile可写?

我成功地使用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而不复制其属性(?)

+0

下面两个由Ignacio Vazquez-Abrams和Saxony的Rolf给出的两个答案都适用:shutil.copyfileobj()和shutil.copyfile()都似乎在复制文件内容的同时使目标文件保持可写。不知道我之前做错了什么,这让我得出结论,他们让我的目标文件是只读的... – RBV

回答

2

打开文件复制文件的内容,只要你喜欢,并使用shutil.copyfileobj()只是该文件的内容从一个到另一个复制。

1

在我的Python盒子上用python 2.7 & python3 shutil.copyfile(inputfile, outputfile)似乎也能工作。