【问题标题】:Python vertical txt concatenation not working properlyPython垂直txt连接无法正常工作
【发布时间】:2014-09-16 04:47:58
【问题描述】:

Concatenate tab-delimited txt files vertically有两种解决方案

假设输入1是

X\tY

输入2是

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

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

如果我跑步

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

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

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

?

【问题讨论】:

    标签: python string-concatenation csv


    【解决方案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')
    

    【讨论】:

    • 我测试了我在修改后的问题上写的版本,它有效。为了澄清和确认,我编辑了我的问题,问你我的理解是否正确。
    • 是的,这就是我的意思。将更新答案以包含完整的示例。
    猜你喜欢
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 2018-04-24
    相关资源
    最近更新 更多