Python-测试文件是否已经打开

时间:2019-05-10 10:10:39

标签: python file

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

这是我的代码:

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:
...

1 个答案:

答案 0 :(得分:-2)

有两种方法: 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.')