使用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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

互联网速递520

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值