删除因读行引起的回车 [英] Deleting carriage returns caused by line reading

查看:39
本文介绍了删除因读行引起的回车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单:

猫狗猴猪

我有一个脚本:

导入系统input_file = open('list.txt', 'r')对于 input_file 中的行:sys.stdout.write('"' + line + '",')

输出为:

"猫,狗,猴,猪",

我愿意:

"猫","狗","猴子","猪",

我无法摆脱处理列表中的行时发生的回车.最后摆脱 , 的奖励点.不知道如何找到并删除最后一个实例.

解决方案

str.rstrip 或简单地 str.strip 是从文件读取的数据中拆分回车(换行)的正确工具.注意 str.strip 将从任一端去除空格.如果您只对剥离换行符感兴趣,只需使用 strip('\n')

换行

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

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

请注意,在您的情况下,一个更简单的解决方案是

<预><代码>>>>从 itertools 导入 imap>>>以 open("list.txt") 作为鳍:打印 ','.join(imap(str.strip, fin))猫、狗、猴、猪

或仅使用列表理解

<预><代码>>>>以 open("test.txt") 作为鳍:打印 ','.join(e.strip('\n') for e in fin)猫、狗、猴、猪

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:
    sys.stdout.write('"' + line + '",')

The output is:

"Cat
","Dog
","Monkey
","Pig",

I'd like:

"Cat","Dog","Monkey","Pig",

I can't get rid of the carriage return that occurs from processing the lines in the list. Bonus point for getting rid of the , at the end. Not sure how to just find and delete the last instance.

解决方案

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

这篇关于删除因读行引起的回车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆