为什么我的readline()不追加到我的列表?

  • 本文关键字:追加 列表 readline python
  • 更新时间 :
  • 英文 :


我试图打开一个文件并将项目附加到名为Apple_data的列表上。变量资源管理器显示我的列表是空的,所以每当我尝试打印它时,只显示[]。我也一直得到一个错误,说"AttributeError: 'list'对象没有属性'readline'。">

我试着改变我的代码后的for循环stock = stock.rstrip('n')和函数读取文件,但不追加到列表仍然。

如何解决这个问题?

def read_file(Apple_stock):

Apple_stock = open("ApplePrices.txt", "r")
Apple_data = []

for stock in Apple_stock:
stock = Apple_stock.readline().rstrip('n')
Apple_data.append(stock)
Apple_stock.close()
return Apple_data
print(Apple_data)

Apple_data是您的列表。你不能在上面调用readline,因为它是一个列表而不是一个文件。你也不需要调用readline因为你已经在for循环中逐行遍历了所以你只需要输入

def read_file(Apple_stock):

Apple_stock = open("ApplePrices.txt", "r")
Apple_data = []

for stock in Apple_stock:
Apple_data.append(stock.rstrip())
Apple_stock.close()
return Apple_data
print(Apple_data)

您也可以使用上下文管理器来处理文件关闭器,并使用列表推导来生成列表

def read_file(stock_data):
with open(stock_data) as stocks:
return [stock.rstrip() for stock in stocks.readlines()]
print(read_file("ApplePrices.txt"))

最新更新