[英]how to print folder name in python?
我正在嘗試使用glob.glob
在所有文件夾中搜索來讀取特定文本文件的多個文件夾。 我只想打印文件夾名稱而不是文件夾名稱/file.txt。
with open ('input.txt', 'w') as i:
for files in glob.glob ('*/*.txt'):
print (files)
我希望我的 output 像
folder1
folder2
folder3
代替
folder1/file.txt
folder2/file2.txt
我看到很多帖子他們使用 os.path ....我確實理解得很清楚
用字符串函數解決這個問題。 試試這段代碼。
with open ('input.txt', 'w') as i:
for files in glob.glob ('*/*.txt'):
print(files.split("/")[0])
解釋:
我們用/
字符分割文件名。 這會生成一個包含兩個項目 folder_name 和 file_name 的列表。 使用索引,我們正在獲取索引為0
的第一個項目。
要測試這個嘗試下面的代碼 -
a = [ "folder1/file.txt", "folder2/file.txt"]
for item in a:
print(item.split("/")[0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.