如何删除空文件 php?
How to remove a file when it's empty php?
我有多个文件。我的脚本在文件中搜索序列名称和序列。如果找到,则格式从 gb 更改为 fasta,仅保留序列名称和序列并将其写回文件中。但有时文件不包含序列名称。在那种情况下,我不向文件写入任何内容,文件为空。这些文件应该被删除,因为在我的脚本末尾,一个 multifasta 是从所有这些文件创建的。
# Find all gb files
$files = glob("*.gb");
foreach ($files as $filename){
$newname = basename($filename, ".gb"). ".fasta";
rename($filename, $newname);
$condition = false;
$lines = file($newname);
foreach($lines as $line) {
if (strstr($line, "ACCESSION") ) {
# Find the line containing the sequence name
$head = str_replace("ACCESSION ","",$line);
$final = "> " . $head;
# check if $head contains text
if ($head == ""){
$condition = true;
}
}
$sequence = trim($line);
# Find the sequence and check the condition
if (preg_match('/^\d/', $sequence) && $condition == false){
$sequence = preg_replace('/[0-9]+/', '', $sequence);
$sequence = preg_replace('/\s/',"",$sequence);
# Store in string
$out .= $sequence;
}
}
# Read lines into file
$f = fopen($newname, "w");
fwrite($f, $t);
fclose($f);
}
# Create multifasta
exec('for f in *fasta; do cat "$f"; echo; done > db', $return);
当文件为空时,我怎样才能最好地删除它,这样它就不会被插入到 multifasta 中。我确信这很简单,但我不知道该怎么做。
最简单的方法是使用filesize
命令,我认为:
if (filesize ( $filename) === 0){
unlink ($filename); //This will delete the file.
continue; //carry on with next file
}
如果由于任何原因无法删除文件,unlink
命令将生成一条错误消息。我不知道你是否需要检查一下。
我有多个文件。我的脚本在文件中搜索序列名称和序列。如果找到,则格式从 gb 更改为 fasta,仅保留序列名称和序列并将其写回文件中。但有时文件不包含序列名称。在那种情况下,我不向文件写入任何内容,文件为空。这些文件应该被删除,因为在我的脚本末尾,一个 multifasta 是从所有这些文件创建的。
# Find all gb files
$files = glob("*.gb");
foreach ($files as $filename){
$newname = basename($filename, ".gb"). ".fasta";
rename($filename, $newname);
$condition = false;
$lines = file($newname);
foreach($lines as $line) {
if (strstr($line, "ACCESSION") ) {
# Find the line containing the sequence name
$head = str_replace("ACCESSION ","",$line);
$final = "> " . $head;
# check if $head contains text
if ($head == ""){
$condition = true;
}
}
$sequence = trim($line);
# Find the sequence and check the condition
if (preg_match('/^\d/', $sequence) && $condition == false){
$sequence = preg_replace('/[0-9]+/', '', $sequence);
$sequence = preg_replace('/\s/',"",$sequence);
# Store in string
$out .= $sequence;
}
}
# Read lines into file
$f = fopen($newname, "w");
fwrite($f, $t);
fclose($f);
}
# Create multifasta
exec('for f in *fasta; do cat "$f"; echo; done > db', $return);
当文件为空时,我怎样才能最好地删除它,这样它就不会被插入到 multifasta 中。我确信这很简单,但我不知道该怎么做。
最简单的方法是使用filesize
命令,我认为:
if (filesize ( $filename) === 0){
unlink ($filename); //This will delete the file.
continue; //carry on with next file
}
如果由于任何原因无法删除文件,unlink
命令将生成一条错误消息。我不知道你是否需要检查一下。