2017-06-20 12 views
0

私は、各ファイルをループして.txtファイルを探した後に、コードの行または数字を辞書に入れたいと思います。ファイル内のファイルを開く方法は?

import os 
cat_dict = {} 
for filename in os.listdir('/home/hello/project/cats/cat'): 
#open files inside the cat directory# 
    for openfile in os.listdir('/home/hello/project/cats/cat' + filename): 
#check if it's a directory 
     if not openfile.endswith('txt.'): continue 
     for line in open(openfile,'r') 
     #if it's the file, open it and get the line 
     if line.startswith('cute'): 
      remember = line.split()[2] 
      cat_dict[filenames] = float(remember) 
      #somehow put it in the dictionary 

しかし、コードを実行した後、私はエラーを得た:

Traceback (most recent call last): 
    File "new.py", line 5, in <module> 
     for openfile in open('/home/hello/project/cat/cat' + filenames): 
IOError: [Errno 2] No such file or directory: '/home/hello/project/cat/cat.DS' 

私はエラーが何であるかを理解していません。私が望むアイテムが辞書の中にあることを確認するにはどうすればいいですか?

答えて

0

私はあなたのファイルを開くために2つのループが必要とは思わない。あなたは1でそれを行うことができます。

dir_path = '/home/hello/project/cats/cat' 

for filename in os.listdir(dir_path): 
    full_path = os.path.join(dir_path, filename) 

あなたは私はあなたが.endswith('.txt')なくtxt.をしたいと考えている、また

with open(full_path) as f: 
    .... # do something with f 

でファイルを開くことができます。

関連する問題