我將首先提到我對 Python 一無所知,但在網上閱讀它可以幫助我解決我的情況。
我想使用(我相信?)一個 Python 腳本來做一些事情。我有一堆 .yml 檔案,我想將其內容傳輸到一個主 .yml 檔案(我們稱之為 Main.yml)。但是,我還希望能夠取每個單獨的 .yml 的名稱,并將其作為“##Name”的內容添加到 Main.yml 中。如果可能,腳本看起來就像目錄中的每個檔案,而不必列出我希望它查找的每個 .yml 檔案(我的目錄只包含 .yml 檔案)。不確定是否需要指定,但以防萬一:我想將所有檔案的內容附加到 Main.yml 并保留縮進(間距)。PS我在Windows上
我想要的示例:
- 檔案:Apes.yml
- 內容:
Documentation:
"Apes":
year: 2009
img: 'link'
運行腳本后,我的 Main.yml 想要:
##Apes.yml
Documentation:
"Apes":
year: 2009
img: 'link'
uj5u.com熱心網友回復:
我也剛開始使用 Python,所以這是一個很好的機會來看看我新學到的技能是否有效!
我想你想使用 os.walk 函式來瀏覽目錄中的所有檔案和檔案夾。
此代碼應該可以作業 - 它假定您的檔案存盤在名為“檔案夾”的檔案夾中,該檔案夾是存盤 Python 腳本的子檔案夾
# This ensures that you have the correct library available
import os
# Open a new file to write to
output_file = open('output.txt','w ')
# This starts the 'walk' through the directory
for folder , sub_folders , files in os.walk("Folder"):
# For each file...
for f in files:
# create the current path using the folder variable plus the file variable
current_path = folder "\\" f
# write the filename & path to the current open file
output_file.write(current_path)
# Open the file to read the contents
current_file = open(current_path, 'r')
# read each line one at a time and then write them to your file
for line in current_file:
output_file.write(line)
# close the file
current_file.close()
#close your output file
output_file.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/477615.html
標籤:python-3.x 列表
上一篇:xpath如何在孩子的數量并不總是相同的情況下獲取第一級孩子的最后一個值
下一篇:將按鈕移動到中心
