簡體   English   中英

如何讀取目錄中的文件,然后出來讀取下一個目錄 python 中的文件?

[英]How do I read files within directory and then come out and read files within next directory python?

我是 python 的新手,我想做這樣的事情 -

 mainDirec/

      subdirec1/ files.... 

      subdirec2/files....     

我如何從 mainDirec go 然后 subdirec1 讀取所有文件然后 go 回來並對 subdirec2 做同樣的事情?

任何幫助表示贊賞。

您無需“進入”目錄/子目錄即可使用 python(或與此相關的任何其他語言)訪問它們。 有兩種類型的路徑:

  1. 絕對(總是從根文件夾開始,例如"/home/username/project/data.txt"

  2. 相對(相對於當前目錄或包含可執行腳本的目錄(如果你有"/home/username/project/script.py""/home/username/project/data.txt" ,如果你想從"script.py"訪問"data.txt" ,它們位於同一目錄中,因此您可以在代碼中使用相對路徑"data.txt""./data.txt"引用它)

您應該閱讀相對/絕對路徑。 事實上,我建議任何初學者閱讀以下教程: https://ryanstutorials.net/linuxtutorial/

相信我,了解文件路徑/操作系統/腳本如何工作的基礎知識是非常寶貴的。

要回答您的問題(假設您只想閱讀subdirec1subdirec2中的文件):

import os

dirs_to_read = ["path/to/subdirec1", "path/to/subdirec2"] # relative or absolute paths of the subdirectories

for dirpath in dirs_to_read:
    for filepath in os.listdir(dirpath):
        # get full filepath since listdir only gets basenames
        filepath = os.path.join(dirpath, filepath)

        # only continue if the current path is a file (ie not a dir)
        if os.path.isfile(filepath):
            with open() as fi:
                fi.read() # read file and do something with it

這是很多縮進,但我留給你做一個更漂亮/更有效的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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