Tag: Name of the color file file GPO usage log body
The difference between Python3.x:os.listdir and Os.walk (Get path method) 1,os.listdir
Usage: Under a directory only file, no folder, this time can use Os.listdir;
For example: The D:\listdir folder has three files (text1.txt, Test2.txt, test3.txt) to get the absolute path of the file:
import os
path = r‘d: \ listdir ’
for filename in os.listdir (path):
#The directory path and file name are spliced together to get the absolute path of the file
print (os.path.join (path, filename))
Output Result:
d:\listdir\test1.txt
d:\listdir\test2.txt
d:\listdir\test3.txt
2,os.walk
Usage: recursive situation, a directory under the existing directory (directories and files may also have a directory and file) also have files, how to read all the files inside, using Os.walk;
For example: The D:\listdir folder has three files (text1.txt, Test2.txt, Test3.txt) and two folders Filedir1 (including file Text1_1.txt, Text1_2. TXT) and Filedir2 (including file Text2_1.txt, Text2_2.txt):
import os
path = r‘d:\listdir‘
for dirpath,dirnames,filenames in os.walk(path):
print(dirpath,dirnames,filenames)
Output Result:
d:\listdir [‘filedir1‘, ‘filedir2‘] [‘test1.txt‘, ‘test2 .txt‘]
d:\listdir\filedir1[] [‘test1_1.txt‘, ‘test1_2.txt‘]
d:\listdir\filedir2[] [‘test2_1.txt‘,‘test2_2.txt‘]
Description: Os.walk Enter a path name in the form of yield (actually a generator) to return a ternary group Dirpath, dirnames, filenames;
Dirpath the path to the directory as a string. such as the above D:\listdir, D:\listdir\filedir1, D:\listdir\filedir2 and so on.
Dirnames lists the names of all the directories that exist under the directory path. For example, there are two directories under D:\listdir: Filedir1 and Filedir2.
Filenames lists the names of all the files under the directory path. Also under D:\listdir there are two files Test1.txt and test2. txt, then these two file names will be listed.
Gets the absolute path of all files below the path:
import os
path = r‘d:\listdir‘
for dirpath,dirnames,filenames in os.walk(path):
for filename in filenames:
print(os.path.join(dirpath,filename))
Output Result:
d:\listdir\test1.txt
d:\listdir\test2.txt
d:\listdir\filedir1\test1_1.txt
d:\listdir\filedir1\test1_2.txt
d:\listdir\filedir2\test2_1.txt
d:\listdir\filedir2\test2_2.txt
The difference between Python3.x:os.listdir and Os.walk (Get Path method)