【问题标题】:Use Python 3 shutil to copy a file AND leave destfile writeable?使用 Python 3 shutil 复制文件并使 destfile 可写?
【发布时间】: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() 似乎都在复制文件内容,同时离开目标文件可写。不知道我之前做错了什么,这让我得出结论,他们将我的目标文件设置为只读...

标签: python shutil


【解决方案1】:

用你喜欢的方式打开文件并使用shutil.copyfileobj() 将文件内容从一个复制到另一个。

【讨论】:

    【解决方案2】:

    在我的带有 python 2.7 和 python3 shutil.copyfile(inputfile, outputfile) 的 linux 机器上似乎也可以正常工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 2023-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多