Getting rid of \n when using .readlines()

This question already has an answer here:

  • Reading a file without newlines 6 answers

  • 这应该做你想做的(列表中的文件内容,按行,没有 n)

    with open(filename) as f:
        mylist = f.read().splitlines() 
    

    I'd do this:

    alist = [line.rstrip() for line in open('filename.txt')]
    

    or:

    with open('filename.txt') as f:
        alist = [line.rstrip() for line in f]
    

    You can use .rstrip('n') to only remove newlines from the end of the string:

    for i in contents:
        alist.append(i.rstrip('n'))
    

    This leaves all other whitespace intact. If you don't care about whitespace at the start and end of your lines, then the big heavy hammer is called .strip() .

    However, since you are reading from a file and are pulling everything into memory anyway, better to use the str.splitlines() method; this splits one string on line separators and returns a list of lines without those separators; use this on the file.read() result and don't use file.readlines() at all:

    alist = t.read().splitlines()
    
    链接地址: http://www.djcxy.com/p/56420.html

    上一篇: 在Python的Cmd.cmd中完成

    下一篇: 在使用.readlines()时摆脱\ n