![](/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.