从多个同时打开的文件行中删除'\n'

2024-09-28 20:16:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要打开一个小但数量可变的文件,每个文件都有相同的行数。然后我需要返回每一行的一个元组。我的代码返回一个元组,但每个元素都保留其'\n';如何在它被塞进元组之前去掉它

这是目前为止的代码

files = ['file1', 'file2', 'file3']
fds = [ open(file) for file in files ] # gets all file open at same time
read_fds = izip( *fds )
for tpl in read_fds:
    print tpl    # will become a 'yield' stmt once the '\n' is sorted
for fd in fds:
    fd.close()

我有一个由3个文件组成的测试集,每个文件有5行,每个行表示文件号和行号。代码打印这些测试文件的准确记录

('f1ln1\n', 'f2ln1\n', 'f3ln1\tthis\tthat\n')
('f1ln2\n', 'f2ln2\n', 'f3ln2\tthis\tthat\n')
('f1ln3\n', 'f2ln3\n', 'f3ln3\tthis\tthat\n')
('f1ln4\n', 'f2ln4\n', 'f3ln4\tthis\tthat\n')
('f1ln5\n', 'f2ln5\n', 'f3ln5\tthis\tthat\n')

到目前为止还不错,但是如何在将“\n”放入元组之前从每一行中剥离它呢

我知道有答案!期待您的建议。谢谢&;祝你今天愉快


Tags: 文件代码inforread数量filesopen
3条回答

我认为最简单的方法是修改对read_fds的赋值,以便从izip生成修改的元组:

read_fds = (tuple(s.rstrip() for s in tup) for tup in izip(*fds))

但是,我没有测试过这个

你也可以使用切片的字符串

for tpl in read_fds:
    list_stripped = []
    for s in tpl:
        list_stripped.append(s[:-1])
    print tuple(list_stripped)

怎么样:

for tpl in read_fds:
    templist = []
    for item in tpl:
        templist.append(item.rstrip("\n"))
    print tuple(templist)

这将删除字符串右侧的任何换行符

相关问题 更多 >