设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
楼主: crossin先生
打印 上一主题 下一主题

【每日一坑 6】 查找文件内容

[复制链接]

0

主题

0

好友

30

积分

新手上路

Rank: 1

楼主
发表于 2017-3-27 22:53:45 |显示全部楼层
  1. #! /usr/bin/env python
  2. #coding=utf-8
  3. import os
  4. rootdir = 'E:\Famine' #定义根目录

  5. #三个参数:分别返回1.父目录 2.父目录下所有文件夹名字(不含路径) 3.父目录下所有文件名字
  6. for father_path, foldernames, filenames in os.walk(rootdir):
  7.    
  8.     for filename in filenames: #遍历文件

  9.         if os.path.splitext(filename)[1] == '.txt': #判断文件后缀是否是txt
  10.             dir = os.path.join(father_path, filename) #组合文件路径
  11.             
  12.             if os.path.exists(dir): #判断文件路径是否存在
  13.                 folder = os.path.split(os.path.split(dir)[0])[1] #获取文件上层文件夹
  14.                 print 'The upper folder is:\n%s' % folder, '\n'
  15.                 print 'The file name is:\n%s' % filename, '\n'
  16.                
  17.                 f = file(dir) #打开文件
  18.                 context = f.read() #读取文件内容
  19.                 print 'The contents of this file is', '\n', context, '\n\n'
  20.                 f.close() #关闭文件
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-4 04:11 , Processed in 0.018383 second(s), 24 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部