簡體   English   中英

如何在 python 中打印文件夾名稱?

[英]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.

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