Skip to content Skip to sidebar Skip to footer

AttributeError: 'list' Object Has No Attribute 'replace' While Trying To Remove '/n'

I've got a bunch of files that I need to rename. I've got the names in order in a text file and I need to remove the linebreaks that are inserted when reading the text file, but I

Solution 1:

The problem is that after split each n in namelist already is a list of strings.

If you want to remove the newlines at the end of the lines, you can either reverse the two comprehensions, to first remove and then split, or just combine them into one. Also, instead of replace, you can use strip to get rid of the newline character at the end of the line.

namelist = [line.strip().split(' ') for line in file]

Solution 2:

.readlines() returns a list of lines, each ending with a \n. There's no point to expect it anywhere else (provided that you use universal newlines when reading the file: mode "r", not "rb").

The whole thing can be made a whole lot shorter is you just iterate over the file (it yields lines, too):

namelist = []
for line in input_file:  
    namelist.extend(line.rstrip('\n').split(' ')) 

As a fun exercise, it can be made a one-liner (a bit less efficient):

namelist = sum((line.rstrip('\n').split(' ') for line in file), [])

Post a Comment for "AttributeError: 'list' Object Has No Attribute 'replace' While Trying To Remove '/n'"