python写入不同的文件
问题描述:
我是一个巨大的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()
答
你的问题是'单词'是一个列表。你不能把它写到你的文件中。您需要将其转换回字符串。另外,在将其转换回来以确保在字符串之间创建所需的间距/分隔时,您需要注意。
你应该这样做。
words = ' '.join(words)
密切关注单引号内的空格。这表明它会在你的字符串之间放置一个空格。
最后,你再做出您的来电:
f2.write(words)
一旦做出这样的转变,我测试你的代码,它成功地分裂,他们写信给你的每规范文件。
+1
甜jeebus谢谢!那就是诀窍。我在我的正则表达式分割下添加了该行,并且能够写入文件。 – chowpay
由于您使用的是“with”,因此您不需要f1.close()和f2.close()。它会自动关闭手柄。 – vahnevileyes
Vahn,谢谢很高兴知道! @hayley,你做了什么编辑(新的堆栈溢出) – chowpay