【问题标题】:How does Python go about reading over lines in a .txt file and split them into a list?Python 如何读取 .txt 文件中的行并将它们拆分为列表?
【发布时间】:2018-11-01 19:13:52
【问题描述】:

所以我很难理解 Python 如何使用 .split() 字符串方法创建列表,如果我要给它一个文件来读取它。

这里有一个包含来自三个不同国家的人口的文本文件,名为 population.txt:

United-States 325700000
Canada        37000000
China         13860000000

在另一个 .py 文件中,我有以下代码:

populationFile = open("population.txt", 'r')

for populationLine in populationFile:
    populationList = populationLine.split()

print(populationList)

populationFile.close()

输出是这样的:

['China', '13860000000']

python 本质上是通过读取每个 来将每个国家和相应的人口放在单独的列表中,就像它对中国所做的那样,还是按字符? 另外,为什么这里只出现一个列表而不是全部?

抱歉所有问题,但我将非常感谢任何可以提供帮助的人:)

【问题讨论】:

  • 如果你想存储每一行​​,你需要追加到一个列表中。

标签: python list file for-loop text


【解决方案1】:

您正在做的是在上一次迭代之上设置 populationList 的值。所以它正在分裂美国人口,然后分裂加拿大人口并将其保存在美国之上,然后中国取代了加拿大。

你可以做什么附加;

populationFile = open("population.txt", 'r')
populationList = [] # create an empty list

for populationLine in populationFile:
    populationList.append(populationLine.split()) # append the split string into list

print(populationList)

populationFile.close()

如果您想对此进行优化,可以使用 with 块。它看起来像这样:

with open("population.txt", 'r') as populationFile:
    populationList = [] # create an empty list

    for populationLine in populationFile:
        populationList.append(populationLine.split()) 

print(populationList)

这只是临时打开文件,当 with 块完成时,它会自动关闭它。

【讨论】:

    【解决方案2】:

    为什么这里只出现一个列表而不是全部?

    populationList 在每次迭代后都会发生变化,并且会丢失(通过覆盖)其先前的值。

    你应该试试这个:

    for populationLine in populationFile:
        populationList.append(populationLine.split()) 
    

    【讨论】:

      【解决方案3】:

      你需要把你的代码改成这个

      populationFile = open("population.txt", 'r')
      
      temp = None   
      # create an empty list
      populationList = []
      
      for line in populationFile:
          # split into different words by the space ' ' character
          temp = line.split()  # temp = ['Canada', '37000000'] or ['China', '13860000000']
      
          # if spaces exist on either the right or left of any the elements in the temp list
          # remove them
          temp = [item.strip() for item in temp[:]]
      
          # append temp to the population list
          populationList.append(temp)
      
      print(populationList)
      
      populationFile.close()
      

      【讨论】:

      • 你应该添加更多解释为什么。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      相关资源
      最近更新 更多