Chr*_*rgo 15 python python-2.7
我有一个清单:
Cat
Dog
Monkey
Pig
Run Code Online (Sandbox Code Playgroud)
我有一个脚本:
import sys
input_file = open('list.txt', 'r')
for line in input_file:
sys.stdout.write('"' + line + '",')
Run Code Online (Sandbox Code Playgroud)
输出是:
"Cat
","Dog
","Monkey
","Pig",
Run Code Online (Sandbox Code Playgroud)
我想要:
"Cat","Dog","Monkey","Pig",
Run Code Online (Sandbox Code Playgroud)
我无法摆脱处理列表中的行所发生的回车.在最后摆脱的奖励点.不知道如何查找和删除最后一个实例.
Abh*_*jit 19
str.rstrip或简单地str.strip是从文件读取的数据中拆分回车符(换行符)的正确工具.注意str.strip将从任一端剥去空白.如果您只对剥离换行感兴趣,请使用strip('\n')
改变线
sys.stdout.write('"' + line + '",')
Run Code Online (Sandbox Code Playgroud)
至
sys.stdout.write('"' + line.strip() + '",')
Run Code Online (Sandbox Code Playgroud)
请注意,在您的情况下,会有一个更简单的解决方案
>>> from itertools import imap
>>> with open("list.txt") as fin:
print ','.join(imap(str.strip, fin))
Cat,Dog,Monkey,Pig
Run Code Online (Sandbox Code Playgroud)
或者只是使用List COmprehension
>>> with open("test.txt") as fin:
print ','.join(e.strip('\n') for e in fin)
Cat,Dog,Monkey,Pig
Run Code Online (Sandbox Code Playgroud)
您可以使用.rstrip()从字符串右侧删除换行符:
line.rstrip('\n')
Run Code Online (Sandbox Code Playgroud)
或者你可以告诉它删除所有空格(包括空格,制表符和回车):
line.rstrip()
Run Code Online (Sandbox Code Playgroud)
它是一个更具体的版本.strip()的方法其去除空格或特定字符从两个字符串的两侧.
对于你的特定情况,你可以坚持一个简单的.strip()但是对于你想要只删除换行符的一般情况,我坚持使用`.rstrip('\n').
我会使用不同的方法来编写你的字符串:
with open('list.txt') as input_file:
print ','.join(['"{}"'.format(line.rstrip('\n')) for line in input_file])
Run Code Online (Sandbox Code Playgroud)
通过使用','.join()你避免使用最后一个逗号,并且使用该str.format()方法比很多字符串连接更容易(更不用说更快).