这只是一个警告,因为我是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个元素。非常感谢。
获得最后一个数字的原因是,在每个循环中,您只将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
下面是一个带有split的实现,它给出了相同的结果。不推荐,因为我们知道每行只有一个项目,所以效率不高。我们只需要去掉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)
我是这样做的:
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)
我希望它能帮助
使用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()
您可以只在一行中执行此操作,使用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)
我们可以试试我的方法伙伴。我当然希望这有帮助,朋友!
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))