鱼C论坛

 找回密码
 立即注册
查看: 1319|回复: 3

[已解决]请教:0基础学python 第30讲 第一题

[复制链接]
发表于 2018-1-17 13:57:50 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
代码:


import os

all_files = os.listdir(os.curdir) # 使用os.curdir表示当前目录更标准
file_dict = dict()

for each_file in all_files:
    if os.path.isfile(each_file):
        file_size = os.path.getsize(each_file)
        file_dict[each_file] = file_size

for each in file_dict.items():
    print('%s【%dBytes】' % (each[0], each[1]))

问题:
为何 os.listdir  里os.curdir 换成其他盘就打印不出东西 例如换成'F:\\tgp',但是可以用 print 打印出F:\\tgp里有什么文件
最佳答案
2018-1-17 14:52:16
lolykong 发表于 2018-1-17 14:33
还是不懂
为什么代码中插入
all_files = os.listdir(‘F:\\’)


对呀 返回了路径下的文件名字的列表呀 但列表的元素只是文件的名字 不能用于继续for循环
需要用根目录拼接成路径 才能去os.path.isfile判断 如果是"f:\\xxx"这种绝对路径就不能继续遍历他os.listdir返回的列表了

os.listdir 只能遍历给定目录下的 不能递归遍历目录下的所有
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2018-1-17 14:02:59 | 显示全部楼层

回帖奖励 +1 鱼币

本帖最后由 sky 于 2018-1-17 14:05 编辑

os.listdir返回包含路径下所有文件和文件夹名字的列表
如果是os.curdir后面的路径使用的就是相对路径
如果你改用绝对路径 后面就需要路径字符串拼接 否则不是有效路径了哦


  1. >>> help(os.listdir)
  2. Help on built-in function listdir in module nt:

  3. listdir(path=None)
  4.     Return a list containing the names of the files in the directory.

  5.     path can be specified as either str or bytes.  If path is bytes,
  6.       the filenames returned will also be bytes; in all other circumstances
  7.       the filenames returned will be str.
  8.     If path is None, uses the path='.'.
  9.     On some platforms, path may also be specified as an open file descriptor;\
  10.       the file descriptor must refer to a directory.
  11.       If this functionality is unavailable, using it raises NotImplementedError.

  12.     The list is in arbitrary order.  It does not include the special
  13.     entries '.' and '..' even if they are present in the directory.
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-1-17 14:33:05 | 显示全部楼层
sky 发表于 2018-1-17 14:02
os.listdir返回包含路径下所有文件和文件夹名字的列表
如果是os.curdir后面的路径使用的就是相对路径
如 ...

还是不懂
为什么代码中插入
all_files = os.listdir(‘F:\\’)
print(all_files)
是可以打印出目录下的所有文件和文件夹啊
那all_file 应该就被赋值了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-1-17 14:52:16 | 显示全部楼层    本楼为最佳答案   
lolykong 发表于 2018-1-17 14:33
还是不懂
为什么代码中插入
all_files = os.listdir(‘F:\\’)


对呀 返回了路径下的文件名字的列表呀 但列表的元素只是文件的名字 不能用于继续for循环
需要用根目录拼接成路径 才能去os.path.isfile判断 如果是"f:\\xxx"这种绝对路径就不能继续遍历他os.listdir返回的列表了

os.listdir 只能遍历给定目录下的 不能递归遍历目录下的所有
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 04:23

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表