2015-10-07 34 views
3

我是一個巨大的python noob。試圖寫一個簡單的腳本,將文件中的一行分割成一個「?」python寫入不同的文件

線在輸入文件(inputlog.log): http://website.com/somejunk.jpg?uniqid&=123&an=1234=123

在輸出文件中的行(outputlog.log): http://website.com/somejunk.jpg uniqid&=123&an=1234=123

這裏的目標是用具有2列的文件,以最終:

這裏是我的代碼,它還挺工作,除了它不會寫入第二個文件

"TypeError: expected a character buffer object"

import re 

a = raw_input("what file do you want to open? ") 
b = raw_input("what is the file you want to save to? ") 

with open(a, 'r') as f1: 
    with open(b,'w') as f2: 
     data = f1.readlines() 
     print "This is the line: ", data #for testing 
     for line in data: 
      words= re.split("[?](.*)$",line) 
      print "Here is the Split: ", words #for testing 
      f2.write(words) 

f1.close() 
f2.close() 
+0

由於您使用的是「with」,因此您不需要f1.close()和f2.close()。它會自動關閉手柄。 – vahnevileyes

+0

Vahn,謝謝很高興知道! @hayley,你做了什麼編輯(新的堆棧溢出) – chowpay

回答

2

你的問題是'單詞'是一個列表。你不能把它寫到你的文件中。您需要將其轉換回字符串。另外,在將其轉換回來以確保在字符串之間創建所需的間距/分隔時,您需要注意。

你應該這樣做。

words = ' '.join(words) 

密切關注單引號內的空格。這表明它會在你的字符串之間放置一個空格。

最後,你再做出您的來電:

f2.write(words) 

一旦做出這樣的轉變,我測試你的代碼,它成功地分裂,他們寫信給你的每規範文件。

+1

甜jeebus謝謝!那就是訣竅。我在我的正則表達式分割下添加了該行,並且能夠寫入文件。 – chowpay