【问题标题】:Python AttributeError: 'list' object has no attribute 'rstrip'Python AttributeError: \'list\' 对象没有属性 \'rstrip\'
【发布时间】:2023-02-15 17:39:45
【问题描述】:
def readFile(CHARACTERS_FILE):
    try:
        charactersFile = open(CHARACTERS_FILE, "r")
        lines = charactersFile.readlines()
        buffer = [lines]
        charactersFile.close
    except:
        print("An error occured.")

    for index in range(len(buffer)):
        buffer[index] = buffer[index].rstrip('\n')

    print(buffer)

    return buffer

总是返回以下错误:

AttributeError: 'list' object has no attribute 'rstrip'

我没有运气剥离这些换行符。帮助??

【问题讨论】:

  • buffer 是一个列表列表。您不能在列表中调用 rstrip(),正如错误所说的那样。
  • 您也不要在文件上调用.close()。您放置了属性,但实际上并没有关闭它。
  • 你为什么做buffer = [lines]

标签: python


【解决方案1】:

您遇到的主要问题是您将lines 列表嵌套在新的单元素列表buffer 中。这似乎是不必要的,并且当您尝试访问字符串但获取列表时,它会导致您的异常。

试试:

buffer = charactersFile.readlines()  # if you don't need lines at all

或者:

lines = charactersFile.readlines()
buffer = list(lines)                 # if you want buffer to be a shallow copy of lines

【讨论】:

    【解决方案2】:

    print("AttributeError: 'list' 对象具有属性 'rstrip'") print("你的代码执行成功")

    【讨论】:

      【解决方案3】:

      buffer = [lines] 删除 buffer = lines 的括号。 这样它就不再是列表了,您可以执行字符串操作。我也遇到过这种错误。

      这是您可以尝试的一些代码

      buffer = [] # to create the list
      # no need for close later. for good practice use 'with'
      with open(CHARACTERS_FILE, "r") as file: 
          lines = file.readlines()
      for x in lines: # x will be each str of your lines.list
          buffer.append(x) # and like this you add them to buffer
          # the string operation you planed later 
          # could be done before appending though but try it yourself 
      

      【讨论】:

      • 我可以哭了,既是因为它是如此简单,也是出于感激。谢谢你!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      • 2016-05-05
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2014-09-08
      相关资源
      最近更新 更多