Python如何读取.txt文件中的行并将它们拆分为一个列表?

2024-10-03 23:28:24 发布

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

因此,如果我要给Python一个要读取的文件,我很难理解Python是如何使用.split()string方法创建列表的。你知道吗

这里我有一个文本文件,里面有来自三个不同国家的人口,叫做人口.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是否像对待中国一样,通过阅读每一行,将每个国家和各自的人口分别列在不同的清单中,还是按字符排列? 另外,为什么这里只出现一个列表而不是全部?你知道吗

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


Tags: 文件方法txt列表string地址国家united
3条回答

how come only one list appears here and not all of them?

populationList在每次迭代后都会发生变化,并丢失(通过覆盖)其早期值。你知道吗

相反,您应该尝试以下方法:

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

您要做的是在上一次迭代的顶部设置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块完成时,它会自动关闭文件。你知道吗

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

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

相关问题 更多 >