Python 文件目录操作
2015-06-29 09:34
681 查看
from os import listdir from os import getcwd from os.path import isfile listdir: 列出当前路径下的所有目录,文件 os.path.isfile: 判断路径是否是文件 os.path.basename: path=‘c:\aa\bb\cc’,则返回cc getcwd, sys.modules[__name__].__file__, sys.argv[0]: 当前的工作路径 __file__: 该模块的路径,包括模块名 __name__和__main__: '__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt. A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported: if __name__ == "__main__": # execute only if run as a script main() For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m. 一个log处理的示例,找到目录下所有的文件中的行,改行包含字符xxx.cn,改行的上一行包含<domain:update,打印出行号 # -*-coding:utf-8 -*- import os from os import listdir from os.path import isfile, join def process_log(): curr_path = os.path.dirname(__file__) onlyfiles = [f for f in listdir(curr_path) if isfile(join(curr_path, f))] all_files = [os.path.join(curr_path, name) for name in onlyfiles if name.find('eppXML.log.2015') >= 0] for one_file in all_files: with open(one_file) as log: lines = log.readlines() n = 0 find_numbers = [] for line in lines: if line.find('<domain:update') >= 0 and lines[n + 1].find('xxx.cn') >= 0: find_numbers.append(n) n += 1 if len(find_numbers) == 0: continue print '%s : %s' % (os.path.basename(one_file), find_numbers)
相关文章推荐
- Python实现函数重载
- Python 入门介绍(整理)
- windows下,python基于SocketServer模拟实现SSH(多线程版)
- Python学习笔记-遍历文件
- PAT Maximum subsequence sum (Python)
- PAT Shuffling machine (Python)
- PAT Have fun with numbers (Python)
- PAT 数组元素循环右移问题 (Python)
- PAT 素数对猜想 (Python)
- PAT 打印沙漏 (Python)
- Scrapy:Python的爬虫框架
- hadoop 流streaming跑python程序
- Python访问纯真IP数据库脚本分享
- 编写Python CGI脚本的教程
- Python数据类型之字典
- Python数据类型之元组
- PAT 最大子列和问题 (Python)
- Python数据类型之列表
- Python字符串处理
- python3.x与python2.x不同点