用counter方法读取文件?

时间:2018-05-06 09:37:38

标签: python

我有一个包含以下内容的文件:

name: James
player: 2

name: Martin
player: 3
.
.

在'之后有一个空格:'名字和玩家后面跟另一个名字和玩家的换行符。

我试图访问詹姆斯和2,马丁和3没有'名称'和'球员'。我计划使用我试过的计数器:

filename = open("testing.txt","r", encoding = "utf-8")
playerFile = filename
lst = []
for line in playerFile:
    line = line.replace('\n','')  #replace newlines with an empty space
    lst.append(line)    #append into a lst for now

counter = 1    #initialize a counter
for i in range(len(lst)):
    if counter == 1:     #for name since name is on first line, hence take the string James
        ...              #how do i get just the string 'James'?
        counter +=1      #increment to go to line 2 which is the player
    elif counter == 2:    #for player
        ...
        counter +=1      #increment to go to line 3 which is a newline
    elif counter == 3:   #newline, empty, set back to 1
        counter = 1    #set back to one since the third line is empty

我们可以假设该文件的格式始终为' name',然后是' player'然后是一条新线'然后是另一个名字'等等。

2 个答案:

答案 0 :(得分:1)

简单就是更好,为什么不迭代这些行并检查它是name还是player所以会相应地采取行动,例如(草稿)

for line in playerFile:
  attr = line.split()
  if atrr[0] == 'name:':
    # store name attr[1]
  elif attr[0] == 'player:':
    # store player attr[1]

注意:您需要处理空白行和包含其他文本的行以及输入文件中的所有方案......

答案 1 :(得分:0)

playerFile = open("testing.txt","r", encoding = "utf-8")
lst = []
for line in playerFile:
  if line!='':
    lst.append(line)    #append into a lst for now

for sen in lst:
  words=sen.split()
  if words[0]=='name:':
    name=words[1]
  else:
    number=words[1]