只是一個警告,我是 python 的初學者,所以如果它超出了我在課堂上學到的知識,我可能會要求澄清答案。
我的文本檔案名為“data.txt”,如下所示(檔案以 80 結尾):
90
100
80
我的代碼如下所示:
data = open('data.txt', 'r')
for line in data:
newLine = line.strip('\n')
dataList = newLine.split('\n')
#This closes the file
data.close()
print('The numbers are ', dataList)
countNumbers = len(dataList)
print('The count of the numbers is ', countNumbers)
當我運行程式時,輸出是:
The numbers are ['80']
The count of the numbers is 1
所以我不明白為什么我沒有取回串列的所有 3 個元素。謝謝你。
uj5u.com熱心網友回復:
您獲得最后一個數字的原因是因為您只是在每個回圈中將 1 項保存到 dataList 變數中,而不是創建串列。您在每個回圈中都覆寫它。
我不確定您的文本檔案是什么樣的,但似乎每行之間都有空格,所以我的 data.txt 檔案看起來像這樣。它有 5 行,3 行有東西,中間有 2 行空白。
90
100
80
好的,這是我的代碼,
data = open('data.txt', 'r')
dataList = [] #create empty list
for line in data:
new = line.strip('\n')
if new: #check if there is data because when you strip a blank new line, you still get an empty string
dataList.append(new) #append line to dataList
data.close()
print('The numbers are ', dataList)
countNumbers = len(dataList)
print('The count of the numbers is ', countNumbers)
這是我的輸出,
The numbers are ['90', '100', '80']
The count of the numbers is 3
這是一個帶有拆分的實作,它給出了相同的結果。不推薦,因為它效率不高,因為我們知道每行只有 1 個專案。我們只需要去掉\n(換行符)。
data = open('data.txt', 'r')
dataList = []
for line in data:
new = line.split('\n')[0] #select first item in array
if new:
dataList.append(new)
print('The numbers are ', dataList)
countNumbers = len(dataList)
print('The count of the numbers is ', countNumbers)
uj5u.com熱心網友回復:
我是這樣做的:
data = open('data.txt', 'r')
dataList = []
for line in data:
if line != "\n":
dataList.append(line.replace("\n",""))
#This closes the file
data.close()
print('The numbers are ', dataList[:])
countNumbers = len(dataList[:])
print('The count of the numbers is ', countNumbers)
我希望它有幫助
uj5u.com熱心網友回復:
使用read方法將整個檔案變成一個字串陣列,然后遍歷檔案:
data = open('data.txt', 'r')
dataList = []
for number in data.read().split("\n"):
if number != '':
dataList.append(int(number))
#This closes the file
data.close()
uj5u.com熱心網友回復:
您可以使用以下方法僅在一行中完成:splitlines
data = open('data.txt', 'r')
dataList = data.read().splitlines() # Put the file line by line in a List
dataList = list(filter(None, dataList)) # Remove all empty list elements
data.close()
print('The numbers are ', dataList)
countNumbers = len(dataList)
print('The count of the numbers is ', countNumbers)
uj5u.com熱心網友回復:
我們可以試試我的方法,伙計。我當然希望這會有所幫助,伙計!
with open('data.txt') as f:
lines_lst = [line.strip() for line in f.read().splitlines()]
[lines_lst.remove(el) for el in lines_lst if el ==""]
print('The numbers are ', lines_lst)
print('The count of the numbers is ', len(lines_lst))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/514423.html
標籤:Python列表文件
上一篇:如何只獲取沒有擴展名的檔案?
