Python 避免将任何内容写入文件

Python 避免将任何内容写入文件,python,grep,Python,Grep,我正在使用Python,还使用egrep选择某些行并创建一个.txt文件,其中包含以下行: os.system('cat {0}|egrep " {1}."|egrep " 7..\."|egrep " 8..\." >> {2}_{1}_800.tim' .format(full,epoch,pname)) 我不确定该怎么做的额外部分是,如果没有匹配行,我不希望写入空白的.txt文件 任何帮助都会很好,谢谢。好的,如果我没弄错的话,你可以使用一些if语句 grep "my pat

我正在使用Python,还使用egrep选择某些行并创建一个.txt文件,其中包含以下行:

os.system('cat {0}|egrep " {1}."|egrep " 7..\."|egrep " 8..\." >> {2}_{1}_800.tim' .format(full,epoch,pname))
我不确定该怎么做的额外部分是,如果没有匹配行,我不希望写入空白的.txt文件


任何帮助都会很好,谢谢。

好的,如果我没弄错的话,你可以使用一些if语句

grep "my pattern" input-file.txt | {
  FILE=output-file.txt
  read x; #Read the first line
  if ! [[ $x ]]; then
    exit #If the 1st line was empty, then there is no match
  fi
  echo $x >> $FILE
  while read line; do
    echo $x
  done >> $FILE
}
这应该很好用。现在,你可以写这个了

'cat {0}|egrep " {1}."|egrep " 7..\."|egrep " 8..\." | 'cat {0}|egrep " {1}."|egrep " 7..\." | egrep " 8..\." | {   FILE={2}_{1}_800.tim;   read x;   if ! [[ $x ]]; then     exit;   fi;   echo $x >> $FILE;   while read line; do     echo $x;   done >> $FILE; }

为什么不使用纯python?如果在命令末尾放置
| | rm{2}{1}u800.tim
,会发生什么?