使用 Python 遍歷文件夾

要解決這個(gè)問題,使用 Python 的標(biāo)準(zhǔn)庫可以很好地完成。我們要做的是遍歷目錄樹,找到所有的 text 文件,讀取內(nèi)容,處理空行和空格,并將處理后的內(nèi)容合并到一個(gè)新的文件中。

整體思路:

  1. 遍歷子目錄:我們可以使用 os 模塊來遍歷目錄中的所有文件。os.walk 是一個(gè)常用的方法,它可以遞歸遍歷指定目錄中的所有文件和子目錄。
  2. 讀取文件并處理內(nèi)容:對(duì)于每個(gè) .txt 文件,我們讀取文件內(nèi)容,刪除空行和空格??梢允褂米址?strip() 方法去除行首和行尾的空格,并且過濾掉空行。
  3. 合并文件內(nèi)容:處理完每個(gè)文件的內(nèi)容后,我們將所有內(nèi)容合并成一個(gè)字符串,準(zhǔn)備寫入到新的文件中。
  4. 寫入新的文件:最后,將合并后的內(nèi)容寫入到一個(gè)新的文本文件中。

Python 實(shí)現(xiàn)步驟

我們可以從文件遍歷開始。先確保能夠遍歷子目錄,然后一步步地實(shí)現(xiàn)每個(gè)細(xì)節(jié)。

步驟 1:遍歷子目錄

在 Python 中,os.walk 是一個(gè)非常強(qiáng)大的函數(shù),可以遞歸遍歷指定目錄下的所有子目錄和文件。它返回的是一個(gè)生成器,生成的是三元組 (dirpath, dirnames, filenames),即當(dāng)前路徑、當(dāng)前路徑下的目錄列表和當(dāng)前路徑下的文件列表。

import os

def list_text_files(root_dir):
    text_files = []
    for dirpath, dirnames, filenames in os.walk(root_dir):
        for file in filenames:
            if file.endswith(".txt"):
                text_files.append(os.path.join(dirpath, file))
    return text_files

在這個(gè)函數(shù)中,我們遍歷了 root_dir 目錄下的所有子目錄及其文件,并將所有 .txt 文件的路徑添加到 text_files 列表中。

步驟 2:讀取文件并刪除空行和空格

為了從文件中刪除空行和空格,我們可以使用 strip() 函數(shù)來處理每一行,并且過濾掉空行。示例代碼如下:

def clean_text_file(file_path):
    cleaned_lines = []
    with open(file_path, 'r', encoding='utf-8') as file:
        for line in file:
            cleaned_line = line.strip()  # 刪除行首尾的空格
            if cleaned_line:  # 過濾空行
                cleaned_lines.append(cleaned_line)
    return cleaned_lines

在這個(gè)函數(shù)中,我們打開每個(gè) .txt 文件,逐行讀取它的內(nèi)容。通過 strip() 函數(shù),我們刪除了每一行的首尾空格。之后,我們過濾掉空行,只保留有內(nèi)容的行。

步驟 3:合并所有文件的內(nèi)容

接下來,我們要把所有清理過的文件內(nèi)容合并在一起。我們可以通過調(diào)用 clean_text_file() 函數(shù)獲取每個(gè)文件的內(nèi)容,并將這些內(nèi)容追加到一個(gè)大列表中。

def merge_cleaned_files(file_paths):
    all_cleaned_lines = []
    for file_path in file_paths:
        cleaned_lines = clean_text_file(file_path)
        all_cleaned_lines.extend(cleaned_lines)
    return all_cleaned_lines

在這個(gè)函數(shù)中,我們遍歷所有的文件路徑,使用 clean_text_file() 函數(shù)清理每個(gè)文件的內(nèi)容,然后將所有清理后的內(nèi)容合并到 all_cleaned_lines 列表中。

步驟 4:寫入新文件

合并后的所有內(nèi)容需要寫入到一個(gè)新的 .txt 文件中。我們可以使用 Python 的 open() 函數(shù)來完成這個(gè)操作。

def write_to_new_file(new_file_path, cleaned_content):
    with open(new_file_path, 'w', encoding='utf-8') as new_file:
        for line in cleaned_content:
            new_file.write(line + '\n')

在這個(gè)函數(shù)中,我們打開一個(gè)新的文件,并將所有清理后的內(nèi)容逐行寫入文件。為了確保每行內(nèi)容之間有換行符,我們?cè)诿恳恍泻竺嫣砑恿?\n。

完整的實(shí)現(xiàn)代碼

將上述步驟整合在一起,形成完整的 Python 腳本:

import os

# Step 1: List all text files in the directory and its subdirectories
def list_text_files(root_dir):
    text_files = []
    for dirpath, dirnames, filenames in os.walk(root_dir):
        for file in filenames:
            if file.endswith(".txt"):
                text_files.append(os.path.join(dirpath, file))
    return text_files

# Step 2: Clean text files by removing blank lines and extra spaces
def clean_text_file(file_path):
    cleaned_lines = []
    with open(file_path, 'r', encoding='utf-8') as file:
        for line in file:
            cleaned_line = line.strip()  # Remove leading and trailing spaces
            if cleaned_line:  # Ignore blank lines
                cleaned_lines.append(cleaned_line)
    return cleaned_lines

# Step 3: Merge the cleaned content of all files
def merge_cleaned_files(file_paths):
    all_cleaned_lines = []
    for file_path in file_paths:
        cleaned_lines = clean_text_file(file_path)
        all_cleaned_lines.extend(cleaned_lines)
    return all_cleaned_lines

# Step 4: Write merged content to a new file
def write_to_new_file(new_file_path, cleaned_content):
    with open(new_file_path, 'w', encoding='utf-8') as new_file:
        for line in cleaned_content:
            new_file.write(line + '\n')

# Main function to orchestrate the process
def process_text_files(root_dir, new_file_path):
    # Step 1: Get all text files
    text_files = list_text_files(root_dir)
    # Step 2 and 3: Clean and merge the content
    cleaned_content = merge_cleaned_files(text_files)
    # Step 4: Write to the new file
    write_to_new_file(new_file_path, cleaned_content)

# Example usage:
root_directory = '/path/to/your/directory'
output_file = '/path/to/your/output_file.txt'
process_text_files(root_directory, output_file)

代碼的解釋

  1. list_text_files 函數(shù):它遍歷了目錄及其子目錄,找到了所有以 .txt 結(jié)尾的文件。文件的完整路徑被保存在 text_files 列表中,便于后續(xù)處理。
  2. clean_text_file 函數(shù):它讀取給定文件的每一行,使用 strip() 函數(shù)清除行首尾的空格。之后,通過判斷 cleaned_line 是否為空來過濾掉空行。如果這行有內(nèi)容,就將它添加到 cleaned_lines 列表中。
  3. merge_cleaned_files 函數(shù):它合并所有文件的內(nèi)容。我們遍歷每個(gè)文件路徑,調(diào)用 clean_text_file 來獲取每個(gè)文件的清理內(nèi)容,然后將這些內(nèi)容合并到一個(gè)大列表中。
  4. write_to_new_file 函數(shù):它將合并后的內(nèi)容寫入到一個(gè)新的文件中。逐行寫入時(shí),通過 line + '\n' 來確保每一行都帶有換行符。

示例說明

假設(shè)有如下目錄結(jié)構(gòu):

/example_directory
    /subdir1
        file1.txt
        file2.txt
    /subdir2
        file3.txt
        file4.txt

每個(gè) .txt 文件可能包含以下內(nèi)容:

  • file1.txt

    Hello World
    
    This is a test.
      
    
  • file2.txt

    Python is fun!
          
    
  • file3.txt

    
    The quick brown fox.
    
    

處理后,每個(gè)文件的內(nèi)容會(huì)刪除空行和空格,結(jié)果將合并為:

Hello World
This is a test.
Python is fun!
The quick brown fox.

最后,所有處理后的內(nèi)容會(huì)被寫入到一個(gè)新的文件中。新的文件將包含所有 .txt 文件中非空行的內(nèi)容,且所有行首尾的空格已經(jīng)被去掉。

關(guān)于性能優(yōu)化

如果處理的文件非常多或非常大,可能會(huì)涉及一些性能優(yōu)化的需求。比如,逐步處理文件而不是一次性讀取所有文件的內(nèi)容,可以避免過大的內(nèi)存占用。以下是一些可能的優(yōu)化方向:

  1. 逐步寫入輸出文件:可以在處理每個(gè)文件時(shí),直接將清理后的內(nèi)容寫入新的文件,而不是等所有文件都處理完再寫入。這樣可以避免在內(nèi)存中存儲(chǔ)過多的數(shù)據(jù)。
  2. 多線程處理:在 Python 中使用多線程或多進(jìn)程模塊(如 threadingmultiprocessing)來同時(shí)處理多個(gè)文件,可以提升處理速度。
  3. 生成器:使用生成器處理文件可以更高效地利用內(nèi)存,特別是在文件內(nèi)容非常大的情況下。

總結(jié)

通過使用 Python 的標(biāo)準(zhǔn)庫 os 和字符串處理功能,我們可以輕松實(shí)現(xiàn)讀取子目錄下所有

.txt 文件,并刪除空行和空格,將處理后的內(nèi)容合并到一個(gè)新的文件中。這個(gè)方法是高效且易擴(kuò)展的,適用于各種目錄結(jié)構(gòu)和文件規(guī)模。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容