歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 使用Python語言高效地處理一個文本文件

使用Python語言高效地處理一個文本文件

日期:2017/3/1 9:45:01   编辑: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 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved