我有上面的樹。我需要以遞回方式搜索樹中的目錄和檔案,并將它們作為字典以下列形式回傳->鍵:目錄/檔案名和值:檔案的第一行
eg: key:1/2/5/test5 value:first line of test 5

到目前為止,我創建了下一個代碼:
def search(root):
items = os.listdir(root)
for element in items:
if os.path.isfile(element):
with open (element) as file:
one_line=file.readline()
print(one_line)
elif os.path.isdir(element):
search(os.path.join(root,element))
問題是我的代碼只搜索目錄。請讓我明白我錯在哪里以及如何解決它。非常感謝任何幫助,謝謝!
uj5u.com熱心網友回復:
您的代碼幾乎是正確的。不過,它必須稍微調整一下。進一步來說,
element是檔案名或目錄名(不是路徑)。如果它是子目錄中的子目錄或檔案,則if os.path.isfile(element)and的值elif os.path.isdir(element)將始終為False。if os.path.isfile(os.path.join(root, element))因此,分別用和替換它們elif os.path.isdir(os.path.join(root, element))。同樣,
with open(element)應替換為with open(os.path.join(root,element))。讀取檔案的第一行時,您必須將路徑和該行存盤在字典中。
呼叫遞回函式時必須更新該字典
elif os.path.isdir(element)。
請參閱下面的完整片段:
import os
def search(root):
my_dict = {} # this is the final dictionary to be populated
for element in os.listdir(root):
if os.path.isfile(os.path.join(root, element)):
try:
with open(os.path.join(root, element)) as file:
my_dict[os.path.join(root, element)] = file.readline() # populate the dictionary
except UnicodeDecodeError:
# This exception handling has been put here to ignore decode errors (some files cannot be read)
pass
elif os.path.isdir(os.path.join(root, element)):
my_dict.update(search(os.path.join(root,element))) # update the current dictionary with the one resulting from the recursive call
return my_dict
print(search('.'))
它列印如下字典:
{
"path/file.csv": "name,surname,grade",
"path/to/file1.txt": "this is the first line of file 1",
"path/to/file2.py": "import os"
}
為了可讀性,os.path.join(root, element)可以存盤在一個變數中,那么:
import os
def search(root):
my_dict = {} # this is the final dictionary to be populated
for element in os.listdir(root):
path = os.path.join(root, element)
if os.path.isfile(path):
with open(path) as file:
my_dict[path] = file.readline()
elif os.path.isdir(path):
my_dict.update(search(path))
return my_dict
print(search('.'))
uj5u.com熱心網友回復:
你可以使用os.walk
以下函式將不包括空檔案夾。
def get_tree(startpath):
tree = {}
for root, dirs, files in os.walk(startpath):
for file in files:
path = root "/" file
with open(path,'r') as f:
first_line = f.readline()
tree[path] = first_line
return tree
輸出將是這樣的:
{
file_path : first_line_of_the_file,
file_path2 : first_line_of_the_file2,
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/411306.html
標籤:
上一篇:連接樹資料-如何簡化我的代碼?
下一篇:用元組在python中構建一棵樹
