![](/img/trans.png)
[英]Reading one 'cell' of a fixed width table (.txt file) that is split over two lines in python/pandas
[英]How does Python go about reading over lines in a .txt file and split them into a list?
因此,如果我要给它一个要读取的文件,那么我很难理解Python如何使用.split()字符串方法创建列表。
在这里,我有一个文本文件,其中包含来自三个不同国家的人口,称为人口.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是否像阅读中国一样逐行地将每个国家和各个人口放在单独的列表中,还是按字符显示? 另外,为什么只有一个列表出现在这里而不是全部?
抱歉所有问题,但是如果有人可以提供帮助,我将非常感激:)
您正在做的是在上一次迭代的顶部设置人口列表的值。 因此它正在分裂美国人口,然后分裂加拿大人口并将其保存在美国之上,然后中国取代了加拿大。
你可以做什么追加?
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()
为什么只有一个列表出现在这里而不是全部?
populationList
在每次迭代后都会更改,并且会丢失(通过覆盖)其先前的值。
相反,您应该尝试以下操作:
for populationLine in populationFile:
populationList.append(populationLine.split())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.