手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

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

[日期:2014-05-01] 来源:Linux社区  作者:Linux [字体:大 中 小]

使用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扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

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

本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-05/101013.htm

linux
相关资讯       Python文本处理 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款