在尝试使用os.walk()遍历特定文件夹来计算我拥有的内存量时遇到一个小问题。似乎可以遍历指定的文件夹(基本上是第一轮)并确定对象是文件还是文件夹。
当它经过第二轮(第一轮的第一个子文件夹)时,就会出现此问题。它不会捕获某些文件,并且会返回错误。
for folderName,subfolders,filenames in os.walk(original_root_folder):
space()
print('The current folder is ' + folderName)
for subfolder in subfolders:
print('SUBFOLDER OF ' + folderName + ': ' + subfolder + ',Size is ',(os.path.getsize(subfolder) / 1000)," KB")
total_size_of_folder = total_size_of_folder + os.path.getsize(subfolder)
for filename in filenames:
print('FILE INSIDE ' + folderName + ': '+ filename + ',(os.path.getsize(filename) / 1000)," KB")
total_size_of_folder = total_size_of_folder + os.path.getsize(filename)
print("Total of folder",(total_size_of_folder/1000)," KB")
这是第一轮的结果,即期望的结果
The current folder is C:\Users\Someone\Desktop
SUBFOLDER OF C:\Users\Someone\Desktop: COMP,Size is 4.096 KB
SUBFOLDER OF C:\Users\Someone\Desktop: compa,Size is 0.0 KB
SUBFOLDER OF C:\Users\Someone\Desktop: compa2,Size is 4.096 KB
SUBFOLDER OF C:\Users\Someone\Desktop: HitFilm Express 2017 Exports,Size is 0.0 KB
这是第二轮
The current folder is C:\Users\Someone\Desktop\COMP
SUBFOLDER OF C:\Users\Someone\Desktop\COMP: comp2402a1,Size is 0.0 KB
FILE INSIDE C:\Users\Someone\Desktop\COMP: comp2402a1.zip,Size is 5.786 KB
这是错误
Traceback (most recent call last):
File "C:/Users/Someone/Desktop/Python testing/reg.py",line 129,in <module>
print('FILE INSIDE ' + folderName + ': '+ filename + '," KB")
File "C:\Users\Someone\AppData\Local\Programs\Python\Python37-32\lib\genericpath.py",line 50,in getsize
return os.stat(filename).st_size
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'input.txt'
我原本希望包含文件“ input.txt”,但显然找不到该文件。