Python 3.x 在python中遍历文件夹时遇到一些问题
我在使用os.walk()遍历特定文件夹时遇到了一个小问题,即试图计算内存量。似乎可以遍历指定的文件夹(基本上是第一轮)并确定对象是文件还是文件夹 当它进入第二轮(第一轮的第一个子文件夹)时会出现问题。它将不会捕获某些文件,并将返回一个错误Python 3.x 在python中遍历文件夹时遇到一些问题,python-3.x,directory,Python 3.x,Directory,我在使用os.walk()遍历特定文件夹时遇到了一个小问题,即试图计算内存量。似乎可以遍历指定的文件夹(基本上是第一轮)并确定对象是文件还是文件夹 当它进入第二轮(第一轮的第一个子文件夹)时会出现问题。它将不会捕获某些文件,并将返回一个错误 for folderName, subfolders, filenames in os.walk(original_root_folder): space() print('The current folder is
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 + ', Size is ', (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 + ', Size is ', (os.path.getsize(filename) / 1000), " 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'
回溯(最近一次呼叫最后一次):
文件“C:/Users/Someone/Desktop/Python testing/reg.py”,第129行,在
打印(“+folderName+”内的文件:“+filename+”,大小为“,(os.path.getsize(filename)/1000),“KB”)
文件“C:\Users\Someone\AppData\Local\Programs\Python\Python37-32\lib\genericpath.py”,第50行,在getsize中
返回os.stat(文件名).st\u大小
FileNotFoundError:[WinError 2]系统找不到指定的文件:“input.txt”
我希望包含文件“input.txt”,但它显然找不到该文件。os.path.getsize()在当前工作目录中运行
替换os.path.getsize(文件名)
使用os.path.getsize(os.path.join(folderName,filename))