list(file)将\ n追加到每一行

时间:2014-11-28 02:27:11

标签: python list file python-2.7

正在阅读文档(https://docs.python.org/2/tutorial/inputoutput.html):

  

要从文件中读取行,可以循环遍历文件对象。这是内存效率高,速度快,并且可以实现简单的代码:

     

如果您想阅读列表中文件的所有行,您还可以使用list(f)f.readlines()

所以我试了一下:

with open(file) as f:
    dictionary = sorted(list(f))
#debug
print dictionary

结果是:

['anuria\n', 'anus\n', 'anuses\n', 'anvil\n', 'anvils\n', 'anxiety\n',
'anxious\n ', 'any\n', 'anybody\n', 'anyhow\n', 'anymore\n',
'anyone\n', 'anyplace\n', 'any thing\n', 'anytime\n', 'anyway\n',
'anywhere\n', 'anywise\n', 'aorta\n', 'aortae \n', 'aortal\n',
'aortas\n', 'aortic\n', 'aortitis\n', 'aoudad\n', 'aoudads\n',
'apace\n', 'apache\n', 'apaches\n', 'apanage\n', 'apart\n',
'apathies\n', 'apathy'...]

两个问题:

  1. 为什么\n换行符会出现?

  2. 有没有办法删除它?或者我必须使用readline()并手动附加?

2 个答案:

答案 0 :(得分:4)

换行符在那里,因为文件中的每一行都以它结束。在读取数据时,Python不会删除此字符。

要删除换行符,您可以使用generator expression并在每一行调用str.rstrip

with open(file) as f:
    dictionary = sorted(line.rstrip() for line in f)

另外,你的变量有点错误; sorted不会返回字典而是返回列表:

>>> sorted(i for i in xrange(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

答案 1 :(得分:3)

您可以做的一些事情:您可以使用strip删除换行符:

with open(file) as f:
    dictionary = sorted(map(str.strip,list(f)))
    #debug
print dictionary

您可以使用切片作为最后一个字符始终是换行符:

dictionary = []
with open(file) as f:
    for x in f:
        dictionary.append(x[:-1])   # it will append everything except last character that is newline
    #debug
print sorted(dictionary)

让lambda去做:

with open(file) as f:
    dictionary = sorted(map(lambda x:x[:-1],f))
    #debug
print dictionary