2014-07-24 28 views
0

有來自Concatenate tab-delimited txt files verticallyPython的垂直TXT拼接不正常

假設輸入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 

突然\噸,碳消失後。

如果我運行

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

如果您在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') 
+0

我測試我對我的修訂問題寫的版本,它的作品。爲了澄清和確認,我編輯了我的問題,問你我的理解是否正確。 – user3123767

+0

是的,那就是我的意思。將更新答案包含完整的示例。 –