I am new to python and i want to do something like this -
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?
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). There are two types of paths:
Absolute (always starts at the root folder eg "/home/username/project/data.txt"
)
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"
)
You should read up on relative/absolute paths. In fact I would suggest any beginner programmer read the following tutorial: 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
):
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.