python writing file statistics script
Idea: use some functions in os module (os.listdir(), os.path.isdir(), os.path.join(), os.path.abspath(), etc.)
Implementation function: display the multi-level directory and the specific file type you want to find (for example, the file ending with ". py"), and read the first line of each file (generally the comment description, so you can roughly understand what this file does)
Write the second level directory file statistics script first
The code is as follows:
#File statistics os.chdir("F:\\pythonstudy") for fp in os.listdir(): if os.path.isdir(fp): print(os.path.join("f:\\pythonstudy",fp)) for f in os.listdir(fp): if f.endswith(".py"): print("\t",os.path.abspath(f)) #Printing f Absolute path of with open(fp+"\\"+f,encoding="utf-8") as f1: print("\t",f1.readline()) #Read first line
The operation effect is as follows:
How to realize the statistics of files in the multi-level directory? Here we use the recursive call method of function to realize
The code is as follows:
#File statistics def sfile(dir,layer=1): print(" "*(layer-1)+dir) for fp in os.listdir(dir): nf=os.path.join(dir,fp) if os.path.isdir(nf): sfile(nf,layer+1) else: if nf.endswith(".py"): #Count files ending with ". py" print(" "*layer+nf,end="\t"*(5-layer)) #layer is for beauty, for tidinesslayer yes
For beauty, layer yes with open(nf,encoding="utf-8") as f1: print(f1.readline().strip()) sfile("f:\\sss")
The operation effect is as follows:
As can be seen in the figure above, the files at the end of ". py" in the multi-level directory are counted and the first line of each file is printed.
If you want to count pictures, you only need to modify them
def sfile(dir,layer=1): print(" "*(layer-1)+dir) for fp in os.listdir(dir): nf=os.path.join(dir,fp) if os.path.isdir(nf): sfile(nf,layer+1) else: if nf.endswith(".jpg"): print(" "*layer+nf,end="\t"*(5-layer)) sfile("f:\\sss")
The operation effect is as follows:
Note: to count some file types under the whole drive letter, the command prompt (cmd) needs administrator permission, otherwise it will prompt to deny access
!! Unsolved problem: how to realize the statistics of all jpg files in "F disk", but do not display (print) the path of no jpg file in the directory, only the path of jpg file in the directory
I'm going to explode. I can't think of it. I'd like to give you some advice