Python垂直txt连接不能正常工作

时间:2014-07-24 14:46:53

标签: python string-concatenation tab-delimited-text

Concatenate tab-delimited txt files vertically

有两种解决方案

假设input1是

X\tY

input2是

A\tB\r\n
C\t\r\n

这里,A,B,C是普通词,\ t是tab。

如果我跑

filenames = [input1, input2]
with open(output, 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write(infile.read().rstrip() + '\n')

然后我得到

X\tY\r\n
A\tB\r\n
C

C消失后突然发现。

如果我跑

filenames = [input1, input2]
with open(output, 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)
        outfile.write("\n")

然后我得到

X\tY\r\n
A\tB\r\n
C\t\r\n
\r\n

我只是想垂直连接。在这种情况下,我需要这个。

X\tY\r\n
A\tB\r\n
C\t\r\n

我使用这两个文件作为示例输入。

https://drive.google.com/file/d/0B1sEqo7wNB1-M3FJS21UTk02Z1k/edit?usp=sharing

https://drive.google.com/file/d/0B1sEqo7wNB1-eWxiTmhKVTJrNjQ/edit?usp=sharing

@pavel_form

你的意思是我必须编码

filenames = [input1, input2]
with open(output, 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write(infile.read().rstrip('\r\n') + '\n')

1 个答案:

答案 0 :(得分:1)

如果您添加参数"将要删除的字符"您的第一个示例将有效。在rstrip调用。像这样:

    outfile.write(infile.read().rstrip('\r\n') + '\n')

所以,完整的例子将是:

    filenames = [input1, input2]
    with open(output, 'w') as outfile:
        for fname in filenames:
            with open(fname) as infile:
                outfile.write(infile.read().rstrip('\r\n') + '\n')