简体   繁体   English

在Python中检查文件是否已打开(由于错误:“文本文件正忙”)

[英]Check if files are open (because of error: “text file busy”) in Python

I have a big pcap file, from which I filter out some packets with tshark, save them in new pcap files and put the filenames of the new pcap files in an array called "filename_array". 我有一个很大的pcap文件,我用tshark过滤掉了一些数据包,将它们保存在新的pcap文件中,然后将新pcap文件的文件名放在一个名为“ filename_array”的数组中。 At the end I delete all the files which are saved in the filename_array. 最后,我删除所有保存在filename_array中的文件。 But one file from this array is still open when the delete process starts and due to that the error "text file busy" occurs. 但是,当删除过程开始时,由于发生“文本文件繁忙”错误,该阵列中的一个文件仍处于打开状态。

So, a solution would be, to check, if all files of the array are closed. 因此,一种解决方案是检查数组的所有文件是否都关闭。 If it's true, I can delete all of them. 如果是这样,我可以删除所有这些。 How can I do this? 我怎样才能做到这一点?

You can check for exception while reading or deleting the file and handle it. 您可以在读取或删除文件并对其进行处理时检查异常。

try:
    with open('filename'):
        #include the file to be deleted in array
except IOError:
    # skip the file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM