目前,在一個非常不方便的地方有大量的 HTML 檔案。每個檔案夾有一個檔案和 2000 多個檔案夾。我想要做的是撰寫一個 python 腳本來打開檔案夾和/或提取它們的內容并將其全部附加到一個檔案中。打開單個檔案沒問題,但是如何從各自的檔案夾中打開多個單獨的檔案?
uj5u.com熱心網友回復:
您可以遍歷檔案夾,os.listdir然后遍歷這些檔案夾中的檔案:
import os
for object in os.listdir(my_dir):
if os.path.isdir(object):
for file in os.listdir(object):
if not os.path.isdir(file):
do_something(file)
uj5u.com熱心網友回復:
我撰寫了一個小代碼,可以幫助您獲取所有 html 檔案(在同一目錄和子目錄中)并將其寫入一個新的 html 檔案。
該函式os.walk()通過自頂向下或自底向上遍歷樹來生成目錄樹中的檔案名。通常獲取根目錄中的所有檔案和子檔案夾
只需編輯下面代碼中的路徑dirName和名稱datafile
# Import Module
import os
# Folder Path
dirName = "D:\\New folder" #specify your root directory name
datafile = open('FileName.html','a ') #specify your file name in which you want to append the data
# Get the list of all files in directory tree at given path
listOfFiles = list()
for (dirpath, dirnames, filenames) in os.walk(dirName):
listOfFiles = [os.path.join(dirpath, file) for file in filenames]
# Read text File
def read_text_file(file_path):
with open(file_path, 'r') as f:
datafile.write(f.read())
datafile.write('\n\n')
# iterate through all file
for file in listOfFiles:
# Check whether file is in html format or not
if file.endswith(".html"):
# call read html file function
read_text_file(file)
datafile.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338414.html
