我在python中相当新。 我正在解析一个大文件,我想检查不同的输入是否正确,特别是如果输入的ID在文件头中。 当我运行以下代码时,我收到此错误消息:
AttributeError:'str'对象没有属性'readlines'
filename = str(raw_input('enter filename: '))
try:
with open(filename, 'rU'): pass
except IOError:
print 'The file does not exist'
sys.exit(0)
def findID(w):
return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search
while True:
ID = (raw_input("Enter ID: ")).upper()
IDheader = ID + ".NA"
with open(filename, 'rU') as f:
first_line = f.readline()
if findID(IDheader)(first_line):
print "you entered ",ID
break
else:
pass
print "ID not in this file."`
for line in filename.readlines():
Line = line.split()
if...
谢谢
答案 0 :(得分:0)
filename
是文件名,而不是文件句柄。你需要打开它:
with open(filename, 'r') as handle:
for line in handle:
line = line.split()