问题描述
我正在尝试编写此代码,以便询问用户要搜索的行,然后输入该行,然后显示用户想要的行。
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'
解决方法
您可以使用以下代码段:
structure(list(diabetes_type_one = structure(c(1L,1L,2L,1L),.Label = c("No","Yes"),class = "factor"),chills = structure(c(1L,class = "factor")),row.names = c(NA,-50L),class = c("tbl_df","tbl","data.frame"))
编辑:使用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
您可能想尝试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)