Home > Back-end >  Python AttributeError: 'list' object has no attribute 'rstrip'
Python AttributeError: 'list' object has no attribute 'rstrip'

Time:12-11

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

Always returns the following error:

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

I'm having no luck stripping these newlines. Help??

CodePudding user response:

The main issue you have is that you're nesting your lines list inside a new one-element list buffer. That seems unnecessary, and it's causing your exception when you try to access the strings but get a list instead.

Try either:

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

or:

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

CodePudding user response:

buffer = [lines] remove the brackets to buffer = lines. This way it's not a list anymore and you can perform your string operation. I had my struggle with this kind of errors too.

Here's some code you can try

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 
  • Related