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

问题描述 投票:0回答:2

我在tf.keras中的代码如下。我想在model_cnn文件夹的每个子目录(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中的驱动器是enter image description here

我的问题是

1)访问子目录中的文件时如何忽略.ipynb_checkpoints?

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

谢谢,D.-H。

python google-colaboratory tf.keras os.walk os.path
2个回答
1
投票

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

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))

0
投票

您可以将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)
© www.soinside.com 2019 - 2024. All rights reserved.