如何忽略或删除 colab 中的“.ipynb_checkpoints”?

How can I ignore or remove ".ipynb_checkpoints" in colab?

我在 tf.keras 中的代码如下。 我想在 model_cnn 文件夹的每个 sub_directory(component_0, component_1) 中检索一个文件 (Xscale.npy)。

root_dir = '/content/drive/My Drive/DeepCID/model_cnn'

    i=0
    for (root, dirs, files) in os.walk(root_dir):
      for d in dirs:
        print(dirs) 
        os.chdir(os.path.join(root, d))
        print(os.getcwd())
        datafile3 = './Xscale.npy'
        Xscale = np.load(datafile3)

错误信息是,

['.ipynb_checkpoints', 'component_0', 'component_1']
/content/drive/My Drive/DeepCID/model_cnn/.ipynb_checkpoints
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-1-862f78aebef9> in <module>()
     57     print(os.getcwd())
     58     datafile3 = './Xscale.npy'
---> 59     Xscale = np.load(datafile3)
     60     Xtest = (Xtest0 - Xscale[0])/Xscale[1]
     61 

/usr/local/lib/python3.6/dist-packages/numpy/lib/npyio.py in load(file, mmap_mode, allow_pickle, fix_imports, encoding)
    426         own_fid = False
    427     else:
--> 428         fid = open(os_fspath(file), "rb")
    429         own_fid = True
    430 

FileNotFoundError: [Errno 2] No such file or directory: './Xscale.npy'

我认识到“.ipynb_checkpoints”是问题所在。 但是,当我查看文件夹时,没有 .ipynb_checkpoints 文件或文件夹。

我在 Colab 中的驱动器是

我的问题是

1) 如何在访问 sub_directories 中的文件时忽略 .ipynb_checkpoints?

2) 为什么 .ipynb_checkpoints 文件在 colab 磁盘中不可见?

提前致谢, D.-H.

将您的代码更改为以下内容。

1) 检查是否为隐藏文件

2) 不使用 os.chdir,因为没有必要。

root_dir = '/content/drive/My Drive/DeepCID/model_cnn'
datafile3 = 'Xscale.npy'

i=0
for (root, dirs, files) in os.walk(root_dir):
    for d in dirs:
        if not d.startswith('.'):
            dir_path = os.path.join(root, d)
            file_path = os.path.join(dir_path, datafile3)
            Xscale = np.load(file_path)

在获取绝对文件路径方面有更优雅的方法,但我想尽量减少更改的代码量。

另一种方法使用 pathlib

from pathlib import Path

root_dir = '/content/drive/My Drive/DeepCID/model_cnn'
datafile3 = 'Xscale.npy'

i=0
for (root, dirs, files) in os.walk(root_dir):
    for d in dirs:
        if not d.startswith('.'):
            fp = Path(root) / d / datafile3
            Xscale = np.load(str(fp))

您可以将 pathlibrglob 结合使用以获得更简洁的代码。

from pathlib import Path

root_dir = '/content/drive/My Drive/DeepCID/model_cnn'
root = Path(root_dir)
# parent dir must not start with dot
for datafile in root.rglob('[!.]*/Xscale.npy'):
  print(datafile)  # or np.load(datafile)

我遇到了同样的问题。发生这种情况的原因可能是在上传期间,它还上传了隐藏文件夹 .ipynb_checkpoint。解决此问题的方法是您可以使用

手动删除文件夹

rmdir /content/drive/My Drive/DeepCID/model_cnn/.ipynb_checkpoints 在执行您提到的代码之前的单元格中。