在loadtxt中阻止或关闭"空文件"警告

Gab*_*iel 11 python numpy

我的代码经过一些文件,用命令将它们读入列表:

data = np.loadtxt(myfile, unpack=True)
Run Code Online (Sandbox Code Playgroud)

其中一些文件是空的(我无法控制),当发生这种情况时,我会在屏幕上显示此警告:

/usr/local/lib/python2.7/dist-packages/numpy/lib/npyio.py:795: UserWarning: loadtxt: Empty input file: "/path_to_file/file.dat"
  warnings.warn('loadtxt: Empty input file: "%s"' % fname)
Run Code Online (Sandbox Code Playgroud)

如何防止此警告显示?

MSa*_*lmo 15

您将必须包装该行catch_warnings,然后调用该simplefilter方法来禁止这些警告.例如:

    with warnings.catch_warnings():
      warnings.simplefilter("ignore")
      data = np.loadtxt(myfile, unpack=True)
Run Code Online (Sandbox Code Playgroud)

应该这样做.

  • 这将隐藏在该行中的_all_警告,而不仅仅是你想要的那个......但是这可能很好,而且由于numpy似乎没有定义警告类别,所以有很好的选择.所以,这似乎是最好的答案. (2认同)
  • 您可以通过使用更高级的“filterwarnings()”方法进一步磨练它,仅在需要时忽略 UserWarnings。一个例子是将 `warnings.simplefilter("ignore")` 行替换为 `warnings.filterwarnings("ignore",category=UserWarning,append=1)` (2认同)