Deleting carriage returns caused by line reading

前端 未结 3 1722
一向
一向 2021-02-18 17:41

I have a list:

Cat
Dog
Monkey
Pig

I have a script:

import sys
input_file = open(\'list.txt\', \'r\')
for line in input_file:
           


        
3条回答
  •  萌比男神i
    2021-02-18 18:03

    str.rstrip or simply str.strip is the right tool to split carriage return (newline) from the data read from the file. Note str.strip will strip of whitespaces from either end. If you are only interested in stripping of newline, just use strip('\n')

    Change the line

     sys.stdout.write('"' + line + '",')
    

    to

    sys.stdout.write('"' + line.strip() + '",')
    

    Note in your case, a more simplistic solution would had been

    >>> from itertools import imap
    >>> with open("list.txt") as fin:
        print ','.join(imap(str.strip, fin))
    
    
    Cat,Dog,Monkey,Pig
    

    or Just using List COmprehension

    >>> with open("test.txt") as fin:
        print ','.join(e.strip('\n') for e in  fin)
    
    
    Cat,Dog,Monkey,Pig
    

提交回复
热议问题