设为首页 加入收藏

TOP

使用Python语言高效地处理一个文本文件
2014-11-23 23:41:52 来源: 作者: 【 】 浏览:9
Tags:使用 Python 语言 高效 处理 一个 文本 文件

使用Python语言高效地处理一个文本文件:


# -- encoding: utf-8 --


# 脚本功能:在指定的文件中查找指定的字符串
# 此脚本接受两个参数
# 参数1:指定一个文件名,在这个文件中查找字符串
# 参数2:指定一个字符串用于查找


from sys import argv
from os.path import exists
# script - 脚本文件自己
# file - 指定操作对象文件名称
# string - 查找字符串
script, file, string = argv


if exists(file) == False:
# 如果文件不存在
print("Error! Specified file %s does not exists." % file)
exit(1)


file_object = open(file, 'r')
line_no = 0 # 行号计数
is_file_end = False # 文件读取是否结束
is_string_found = False # 字符串是否找到
while is_string_found == False and is_file_end == False:
# 如果字符串还未找到并且文件还未结束,执行循环
file_line_data = file_object.readline()
line_no += 1
if file_line_data != "":
if string in file_line_data:
# 如果找到了指定的字符串
is_string_found = True
else:
is_string_found = False
else:
# print("File read end.")
is_file_end = True


# 判断查找结果
if is_string_found == False:
print("Specified string %r cannot be found in specified file %r." % (string, file))
else:
print("Specified string %r has be found! and it's on %d line." % (string, line_no))


file_object.close()


推荐阅读:


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Python ctypes中void**的表示 下一篇Groovy 2.3 trait语法介绍

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: