因此,如果我要给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是否像对待中国一样,通过阅读每一行,将每个国家和各自的人口分别列在不同的清单中,还是按字符排列? 另外,为什么这里只出现一个列表而不是全部?你知道吗
抱歉,所有的问题,但我将非常感谢任何人谁可以帮助:)
populationList
在每次迭代后都会发生变化,并丢失(通过覆盖)其早期值。你知道吗相反,您应该尝试以下方法:
您要做的是在上一次迭代的顶部设置populationList的值。所以它分裂了美国的人口,然后分裂了加拿大的人口,在美国的基础上拯救了加拿大,然后中国取代了加拿大。你知道吗
你能做什么
如果您想对此进行优化,可以使用with块。它看起来是这样的:
这只会临时打开文件,当with块完成时,它会自动关闭文件。你知道吗
你需要把你的代码改成这个
相关问题 更多 >
编程相关推荐