0

这个小助手函数写入results一个 excel 文件。如果文件已经存在并且overwrite设置了标志,则应尽可能覆盖文件 - 即当文件未被任何其他应用程序(在本例中为 Excel)打开时:

def writeXls(results, fname, overwrite=False):
  if os.path.isfile(fname) and not overwrite:
    print("Error: can't write to {} because it already exists and overwrite flag is false".format(fname))
    return

  # doesn't work as intended but write access should be checked first. Fix this.
  if not os.access(fname, os.W_OK):
    print("Error: can't write to {} because write access is not allowed. It might be already opened by other software.".format(fname))

问题是 W_OK 的测试通过了,即使文件是在 Excel 中打开的:

f = open(file_name_or_filelike_obj, 'w+b')
IOError: [Errno 13] Permission denied: <fname here>
  • 为什么呢
  • 我应该如何测试对文件的写访问权限?
4

0 回答 0