Python中写入文件的错误预期的串/缓冲

Python中写入文件的错误预期的串/缓冲

问题描述:

我有一个代码将取代由特定的关键字文本反复, 问题:当我提供了一个文件作为输入,我得到错误Python中写入文件的错误预期的串/缓冲

编码:(当文字是做工不错内码)

import re, itertools 
car = ['skoda', 'audi', 'benz'] 
text = """ 
I have a car="mycar" 
My friend has a vehicle="myvehicle" 
     My uncle have a car="mycar" 
Second verse same as the first 
""" 
it = itertools.cycle(car) 
newtext = re.sub(r'mycar|myvehicle', lambda _: next(it), text) 
print newtext 

编码提供:当文件作为输入

import re, itertools 
car = ['skoda', 'audi', 'benz'] 

with open('ckili.txt','r') as text: 
    text1=text.readlines() 
    it = itertools.cycle(keywords2) 
    newtext = re.sub(r'mycar|myvehicle', lambda _: next(it), text1) 

with open('ckili.txt','w') as f: 
    f.write(newtext)  

我得到的错误为:

File "C:\Python27\replmay.py", line 8, in <module> 
    newtext = re.sub(r'mycar|myvehicle', lambda _: next(it), text) 
    File "C:\Python27\lib\re.py", line 151, in sub 
    return _compile(pattern, flags).sub(repl, string, count) 
TypeError: expected string or buffer 
>>> 

请帮我把输出写入文件!

您的回溯与您的代码不符。在你的回溯中,使用了text,这是一个文件对象

不是您的代码与text1一起工作;这是一个列表,而不是str。代替使用readlines()的,使用read()

with open('ckili.txt','r') as fileob: 
    text = fileob.read() 
    it = itertools.cycle(keywords2) 
    newtext = re.sub(r'mycar|myvehicle', lambda _: next(it), text) 

或分别处理每一行。请注意,我冒昧地稍微改了一些名字; text不是文件对象的最佳名称。

您似乎在将模块导入交互式解释器。知道模块导入已被缓存,您需要明确地重新启动解释器或在更改后重新加载模块。

+0

谢谢你回答完美的方式! – 2014-09-03 18:22:27