简体   繁体   English

Python如何去读取.txt文件中的行并将其拆分为列表?

[英]How does Python go about reading over lines in a .txt file and split them into a list?

So I am having trouble understanding how Python creates lists using the .split() string method if I were to give it a file to read. 因此,如果我要给它一个要读取的文件,那么我很难理解Python如何使用.split()字符串方法创建列表。

Here I have a text file with populations from three different countries called population.txt: 在这里,我有一个文本文件,其中包含来自三个不同国家的人口,称为人口.txt:

United-States 325700000
Canada        37000000
China         13860000000

and in another .py file, I have this code: 在另一个.py文件中,我有以下代码:

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

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

print(populationList)

populationFile.close()

The output is this: 输出是这样的:

['China', '13860000000']

Does python essentially put each country and the respective population in separate lists by reading each line as it did with China, or is it by character? python是否像阅读中国一样逐行地将每个国家和各个人口放在单独的列表中,还是按字符显示? Also, how come only one list appears here and not all of them? 另外,为什么只有一个列表出现在这里而不是全部?

Sorry for all the questions, but I will be very grateful for anyone who can help :) 抱歉所有问题,但是如果有人可以提供帮助,我将非常感激:)

What you are doing is setting the value for populationList on top of the previous iteration. 您正在做的是在上一次迭代的顶部设置人口列表的值。 so it is splitting the United States population, then splitting the Canada population and saving it over the United States, then China replaced Canada. 因此它正在分裂美国人口,然后分裂加拿大人口并将其保存在美国之上,然后中国取代了加拿大。

What you can do it append; 你可以做什么追加?

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()

If you would like to optimize this, you can use a with block. 如果您想对此进行优化,可以使用with块。 It would look like this: 它看起来像这样:

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

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

print(populationList)

This only opens the file temporarily and when the with block is complete, it closes it automatically. 这只会临时打开文件,并且在with块完成时,它将自动关闭文件。

You need to change your code to this 您需要将代码更改为此

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()

how come only one list appears here and not all of them? 为什么只有一个列表出现在这里而不是全部?

populationList is changing after each iteration and losing (by overwriting) its earlier value. populationList在每次迭代后都会更改,并且会丢失(通过覆盖)其先前的值。

Instead you should try this: 相反,您应该尝试以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM