Python3查找指定字符串在文件中的行数位置并输出
#! /usr/local/bin/python3
# -*- coding:UTF-8 -*-
import os
# 确定当前操作系统路径分隔符
def path():
global pathSeparator
osName = os.name
if osName == "posix":
pathSeparator = "/"
elif osName == "nt":
pathSeparator = "\\"
# 主程序
def main():
cwd = os.getcwd()+pathSeparator
print("\n当前绝对路径: "+cwd)
filePath = input("输入文件相对或绝对路径(输入q退出): ")
if filePath == 'q':
exit()
# 判断是否绝对路径.如果否,转换为绝对路径
while not(os.path.isabs(filePath)):
filePath = cwd+filePath
# 判断路径是否存在.如果否,重新输入
while not(os.path.exists(filePath)):
filePath = input("文件未找到.\n\
请重新输入文件路径: ")
# 判断路径是否文件.如果否,重新输入
while not(os.path.isfile(filePath)):
filePath = input("输入的路径不是文件.\n请重新输入文件路径: ")
string = input("输入要查找的字符串: ")
print()
# 开始查找
count = 0
f = open(filePath, "r")
for line in f.readlines():
if string in line:
print("第 "+str(count)+" 行已找到.")
print("该行内容: \n"+line)
count += 1
f.close()
if __name__ == "__main__":
path()
while True:
main()
版权声明:本文为qq_46919160原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。