【问题标题】:Python - test if a file has already been openPython - 测试文件是否已经打开
【发布时间】:2019-05-10 10:10:38
【问题描述】:

我会在写入之前测试文件是否已经打开。

这是我的代码:

with open(file_five, 'w') as f:
    f.write(xml)

我想要这个代码示例:

if "file_five has already been open"
        with open(file_five, 'w') as f:
           f.write(xml)
else:
...

【问题讨论】:

  • 脚本之前或以前打开过的“已打开”是什么意思?
  • 是的。由脚本打开
  • @FedericoklezCulloca 不确定是否是完全相同的问题。我认为 OP 想知道该文件过去是否已打开,而不是现在是否打开该文件.... 或者我完全误解了:D
  • 有区别吗?无论如何你都会覆盖文件......在这个过程中截断它。

标签: python file


【解决方案1】:

有两种方法: 1-> 针对 Excel

try:
    myfile = open("file_five.csv", "r+") # or "a+", whatever you need
except IOError:
    print "Could not open file! !"

with myfile:
    do_stuff()

2 -> 对于任何文件(重命名方法

import os

try: 
    os.rename('file.xls', 'tempfile.xls')
    os.rename('tempfile.xls', 'file.xls')
except OSError:
    print('File is still open.')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 2019-04-29
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多