Python vertical txt concatenation not working properly

╄→гoц情女王★ 提交于 2019-12-25 03:41:47

问题


There are two solutions from Concatenate tab-delimited txt files vertically

Suppose input1 is

X\tY

input2 is

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

Here, A, B, C are ordinary words and \t is tab.

If I run

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

then I get

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

Suddenly \t after C disappears.

If I run

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")

then I get

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

I simply want to concatenate vertically. In this case, I would need this.

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

I used these two files as example inputs.

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

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

@pavel_form

Do you mean I have to code

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:


Your first example will work if you add parameter "what chars to strip" in rstrip call. Like this:

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

So, the complete example will be:

    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')


来源:https://stackoverflow.com/questions/24936955/python-vertical-txt-concatenation-not-working-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!