2017-06-20 109 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個循環來打開你的文件。你可以用一個做到這一點:

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

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

您可以打開該文件

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

而且,我相信你想.endswith('.txt'),而不是txt.