使用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开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码]

Python脚本获取Linux系统信息

Python 的详细介绍:请点这里
Python 的下载地址:请点这里

本文永久更新链接地址:

相关内容

    暂无相关文章