如何从txt文件列表中读取元素(python)

2024-06-25 23:35:03 发布

您现在位置:Python中文网/ 问答频道 /正文

正如主题所说,我需要python代码方面的帮助。 当我用1输入ID时,它会打印

"Error 
None"

我猜,无来自打印(grp)。顺便说一句,我不熟悉这种编码。我只知道[file=open(“…”,“r')]这类。。这里是python新手

def hihi(ID):
  file=open('a.txt','r')
  iden=ID
  try:
        for line in file.readlines():
           line1=line.split('\t')
           if line1[1]==1:
               if (line1[0]==iden):
               grp=line1[3]
    file.close()
    return grp
    except:
        print('Error')
        return
ID=int(input('Enter ID'))
grp=hihi(ID)
print(grp)

“a.txt”文件记录如下:

1\t a\t 11\t ATO\t 2\t y\t 000\t aaa


Tags: 代码txtid主题returniflineerror
1条回答
网友
1楼 · 发布于 2024-06-25 23:35:03

我先确定身份。我加了…作为。。因此,您最终不必关闭该文件

def hihi(ID):
  with open('a.txt','r') as file:
    # Removed 'iden=ID' because you can just use 'ID'

    try:
      for line in file.readlines():
        line1 = line.split('\t')

        if line1[1] is '1 ': # The first item in 'line1' is '1 ' (note the extra space)
          if line1[0] is str(ID): # 'line1[0]' returns the first char, which is '1', I casted the ID to a string to compare them
            grp = line1[3] # 'line1' is a list of only 2 items, so only 'line1[0]' and 'line1[1]' return something

      return grp

    except Exception as e:
      print(e) # Print the stacktrace
      return

ID = int(input('Enter ID'))
grp = hihi(ID)
print(grp)
# grp didn't receive a value because 'hihi' causes an error and returns 'None' instead of a value

首先打印stacktrace,查看行读取器导致错误的原因

相关问题 更多 >