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

来源:互联网 发布:免费进销存软件排名 编辑:程序博客网 时间:2024/06/06 03:34
# -- encoding: utf-8 --# 脚本功能:在指定的文件中查找指定的字符串# 此脚本接受两个参数# 参数1:指定一个文件名,在这个文件中查找字符串# 参数2:指定一个字符串用于查找from sys import argvfrom os.path import exists# script - 脚本文件自己# file - 指定操作对象文件名称# string - 查找字符串script, file, string = argvif 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 += 1if file_line_data != "":if string in file_line_data:# 如果找到了指定的字符串is_string_found = Trueelse:is_string_found = Falseelse:# 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()

原创粉丝点击