|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
晚上用os和os.path模块写了个统计目录下文件大小的小程序,结果访问E盘时出现错误:
- 请输入目录:E://
- Traceback (most recent call last):
- File "E:/Python/文件大小统计.py", line 13, in <module>
- file_size(file_contents) if os.path.exists(file_contents) else print('目录错误!')
- File "E:/Python/文件大小统计.py", line 8, in file_size
- print('{a} 【{b}Bytes】'.format(a=each, b=os.path.getsize(each)))
- File "C:\Users\yg\AppData\Local\Programs\Python\Python36\lib\genericpath.py", line 50, in getsize
- return os.stat(filename).st_size
- FileNotFoundError: [WinError 2] 系统找不到指定的文件。: '$RECYCLE.BIN'
- Process finished with exit code 1
复制代码
代码如下:
- import os
- import os.path
- def file_size(contents):
- file_list = os.listdir(contents)
- for each in file_list:
- print('{a} 【{b}Bytes】'.format(a=each, b=os.path.getsize(each)))
- while True:
- file_contents = input('请输入目录:')
- file_size(file_contents) if os.path.exists(file_contents) else print('目录错误!')
复制代码
如果你想查询任意路径下的文件大小,就得改变路径去你要查询的地方,一般情况下,子文件夹下面的程序是无法访问父文件夹目录的。我给你添加了修改路径的函数,现在可以随意访问有权限的路径了。
import os
import os.path
def file_size(contents):
file_list = os.listdir(contents)
for each in file_list:
print('{a} 【{b}Bytes】'.format(a=each, b=os.path.getsize(each)))
while True:
file_contents = input('请输入目录:')
if os.path.isdir(file_contents):
os.chdir(file_contents)
file_size(file_contents) if os.path.exists(file_contents) else print('目录错误!')
|
|