AttributeError: 'list' 对象在尝试删除 '/n' 时没有属性 'replace' [英] AttributeError: 'list' object has no attribute 'replace' while trying to remove '/n'
问题描述
我有一堆文件需要重命名.我在文本文件中按顺序获得了名称,我需要删除读取文本文件时插入的换行符,但我不断收到此错误.AttributeError: 'list' 对象在尝试删除 '/n' 时没有属性 'replace'
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 keep getting this error. AttributeError: 'list' object has no attribute 'replace' while trying to remove '/n'
感谢任何和所有帮助,我真的不知道我在做什么.
Any and all help is appreciated, I really don't know what I'm doing.
from os import rename, listdir
fnames = listdir('.')
file = open("names.txt", "r")
namelist = [line.split(' ') for line in file.readlines()]
namelist = [n.replace('
', '') for n in namelist]
print (namelist)
推荐答案
问题是split
之后namelist
中的每个n
已经是一个列表字符串.
The problem is that after split
each n
in namelist
already is a list of strings.
如果你想去掉行尾的换行符,你可以把这两种理解颠倒过来,先remove
然后split
,或者只是合并它们成一.此外,您可以使用 strip
来去除行尾的换行符,而不是 replace
.
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]
这篇关于AttributeError: 'list' 对象在尝试删除 '/n' 时没有属性 'replace'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!