python高效处理文件_使用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 的詳細介紹:請點這里
Python 的下載地址:請點這里
總結
以上是生活随笔為你收集整理的python高效处理文件_使用Python语言高效地处理一个文本文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python实现关联算法_python使
- 下一篇: 计算机软件名称用什么符号,[计算机软件及