简体   繁体   English

如何读取目录中的文件,然后出来读取下一个目录 python 中的文件?

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

I am new to python and i want to do something like this -我是 python 的新手,我想做这样的事情 -

 mainDirec/

      subdirec1/ files.... 

      subdirec2/files....     

How do I go from mainDirec then subdirec1 and read all files and then go back and do the same for subdirec2?我如何从 mainDirec go 然后 subdirec1 读取所有文件然后 go 回来并对 subdirec2 做同样的事情?

Any help is appreciated.任何帮助表示赞赏。

You don't need to "go into" directories/subdirectories to access them in python (or any other language for that matter).您无需“进入”目录/子目录即可使用 python(或与此相关的任何其他语言)访问它们。 There are two types of paths:有两种类型的路径:

  1. Absolute (always starts at the root folder eg "/home/username/project/data.txt" )绝对(总是从根文件夹开始,例如"/home/username/project/data.txt"

  2. Relative (relative to the current directory or directory in which an executable script is contained (if you have "/home/username/project/script.py" and "/home/username/project/data.txt" , if you want to access "data.txt" from "script.py" , they are in the same dir so you can reference it in your code with the relative path "data.txt" or "./data.txt" )相对(相对于当前目录或包含可执行脚本的目录(如果你有"/home/username/project/script.py""/home/username/project/data.txt" ,如果你想从"script.py"访问"data.txt" ,它们位于同一目录中,因此您可以在代码中使用相对路径"data.txt""./data.txt"引用它)

You should read up on relative/absolute paths.您应该阅读相对/绝对路径。 In fact I would suggest any beginner programmer read the following tutorial: https://ryanstutorials.net/linuxtutorial/事实上,我建议任何初学者阅读以下教程: https://ryanstutorials.net/linuxtutorial/

Trust me, it is invaluable to know the basics of how filepaths/operating systems/scripts work.相信我,了解文件路径/操作系统/脚本如何工作的基础知识是非常宝贵的。

To answer you're question (assuming you're looking to ONLY read the files in subdirec1 and subdirec2 ):要回答您的问题(假设您只想阅读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

This is a lot of indents, but I leave it to you to make a prettier/more efficient solution.这是很多缩进,但我留给你做一个更漂亮/更有效的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM