使用 Perl 检查文件是否在 Excel 中打开

Check whether a file is opened in Excel using Perl

我目前可以使用此代码检查扩展名为 .csv 的 CSV 文件是否打开

if (-e $filename) {
    if (open(TXT,">>$filename")){
        #file is closed 
    } 
    else {
        #file is open
    }  
} 

如果我尝试使用 .txt 文件而不是 .csv 文件,则测试失败。它失败意味着即使我打开文件时代码也会执行 if 语句,而它应该执行代码的 else 语句。

但是如果我使用 Excel 打开 .txt 文件,它也会失败。

使用记事本或Excel打开文件,如何保证测试成功?

我检查了另一个 post How do you check if a file is open using Perl? 但它对我不起作用。有人可以建议如何解决这个问题吗?

更新:

if (-e $filename) {
    if (open(TXT,">>$filename")){
          #file is not in use   
    } else {
          #file is in use
}  

如果我用答案中提到的代码替换上面的代码

open TF, "<$filename" or die "unable to open file $!"; #open the existing file
if(<TF>){
    close TXT;  
} else {
    goto END;

}

它不起作用。也许我在打开现有文件的地方犯了一个语法错误。 ?

试试这个,或者你也可以用另一个做同样的事情

open TF, "<test.txt" or die "unable to open file $!"; #open the existing test.txt file

if(<TF>)
{
       print "file is open";
}
else
{
    print "There might an issue with this file";
}

如果您想检查文件处理程序是否打开,试试这个

 open TF, ">>test1.txt" or die "unable to open file $!";

    if(tell(TF) != -1)
    {

        print "file is open";

    }
    else
    {
        print "There might an issue with this file";
    }

tell 报告您在文件中的位置。如果它是 -1 这是一个无效的位置意味着你不在文件中的任何地方。