Python垂直txt连接无法正常工作 [英] Python vertical txt concatenation not working properly

查看:38
本文介绍了Python垂直txt连接无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

垂直连接制表符分隔的txt文件有两种解决方案

假设 input1 是

Suppose input1 is

X\tY

input2 是

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

这里A、B、C是普通词,\t是制表符.

Here, A, B, C are ordinary words and \t is 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 消失后突然\t.

如果我跑

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

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

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

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

?

推荐答案

如果您在 rstrip 调用中添加参数要剥离的字符",您的第一个示例将起作用.像这样:

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

所以,完整的例子是:

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

这篇关于Python垂直txt连接无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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