简体   繁体   中英

Python writing to file errors expected string/buffer

I have a code which will replace specific text from keywords iteratively, Problem:When i provide a file as input i get error

Coding:(works good when text is provided within code)

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

Coding: when file as input

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)    

I get error as:

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

Please help me to write output into a file!

Your traceback doesn't match your code. In your traceback, text is used, which is a file object .

Not that your code works with text1 either; that is a list , not a str . Instead of using readlines() , use 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)

or process each line separately. Note that I took the liberty to change the names a little; text isn't the best name for a file object.

You appear to be importing the module into your interactive interpreter. Know that module imports are cached, you'll need to explicitly restart your interpreter or reload the module after changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM