Python3查找指定字符串在文件中的行数位置并输出
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()