簡體   English   中英

如何使用 glob.glob 中的 output 讀取輸出文件?

[英]How to use the output from glob.glob to read the outputted file?

我正在編寫一個程序來掃描特定文件類型並讀取它們以獲取某些“命令”。 我有代碼filenameglob = (glob.glob("*.doremi"))但是在使用print返回變量時,它會顯示為['test.doremi']而不是最佳test.doremi 這個問題是我不能用它來讀取文件。 我將如何 go 關於使用 glob 搜索文件 output 名稱然后讀取具有該名稱的文件?

基本答案

glob.glob返回與運行時傳遞的搜索條件匹配的項目列表,如果未找到匹配項,則返回空列表。 這就是你得到['test.doremi']而不是test.doremi的原因。

您的示例中的filenameglob變量是一個包含 1 個元素的列表 - 字符串test.doremi - 可以使用列表中的索引訪問它,即filenameglob[0]test.doremi

假設目標目錄中將有 0 或 1 個.doremi文件,以下代碼為您的原始問題提供了適當的答案/解決方案。

import glob

filenameglob = glob.glob("*.doremi")

if filenameglob: # If glob.glob returned list of matches
    filename = filenameglob[0] # Take first item from filename glob
    print(filename)
    with open(filename, "r") as f: # Open file in read mode
        contents = f.read() # Read contents from file to variable
    # Do something with contents read from .doremi file
    
else: # Else if glob.glob returned empty list
    print("No .doremi file found!")
    # Define behaviour in case of no .doremi file found

處理目錄中的多個.doremi文件

根據您的原始問題,上面的代碼假定執行目錄中有 0 或 1 個擴展名為.doremi的文件。

如上所述, glob.glob返回表示匹配的字符串列表 - 在本例中為'*.doremi'

因此,如果glob.glob在執行目錄中找到多個.doremi文件,可能值得考慮如何處理它們。

一種解決方案可能是編寫一個 function 定義如何處理從每個.doremi文件讀取的內容,並在循環中為glob.glob返回的每個項目調用它。 有關如何執行此操作的示例,請參見下文。

import glob

def process_contents(contents):
    # Process file contents here

filenameglob = glob.glob("*.txt")

if filenameglob: # If glob.glob returned list of matches
    for filename in filenameglob: # For each file in filenameglob list
        print(filename)
        with open(filename, "r") as f: # Open current file in read mode
            contents = f.read() # Read contents from current file to variable
            process_contents(contents) # Send contents from file to function for processing
            
else: # Else if glob.glob returned empty list
    print("No .doremi files found!")
    # Define behaviour in case of no .doremi files found

上面的代碼適用於glob.glob返回的任意數量 (0...n) 的文件,因此我建議采用這種方法來更好地降低代碼處理“錯誤” .doremi文件的風險 - 如可能發生在基本答案中,因為它只會處理列表中的第一個,即使存在多個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM