![](/img/trans.png)
[英]Get a file line input from user, read from a file, return only the int value present on the inputted user line number
[英]How to get script to read file, accept user input, and display specific line from user input
我正在尝试编写此代码,以便询问用户要搜索的行,然后他们输入它,然后显示用户想要的行。
import os
f = open("input_file_lab_1.txt","r")
allData = f.read()#3
cleanedData = allData.split("\n")
name = input("enter line to search\n").strip()
n = 0
while n == 0:
for line in range(len(cleanedData)):
if name in cleanedData[line]:
print(name)
n = 1
else:
pass
f.close()
不知道有没有更简单的方法。 我也不断收到错误
File "os1.py", line 7, in <module>
name = input("enter line to search\n").strip()#5
AttributeError: 'int' object has no attribute 'strip'
您可以使用此代码段:
import os
with open("input.txt","r") as f:
name = input("enter line to search\n").strip()
for line in f:
if name in line:
print(line)
break
编辑:如@alec_djinn 建议的那样使用with statement
而不是f.open()/close()
你可能想试试 python 的标准库
https://docs.python.org/3/library/linecache.html#module-linecache
import linecache
lineNumber = input("enter line to search\n").strip()
line = linecache.getline(fileName, lineNumber)
print(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.