Skip to content Skip to sidebar Skip to footer

Typeerror: Expected String Or Buffer | Python

I've been trying to parse a text file and manipulate it with regular expressions. This is my script: import re original_file = open('jokes.txt', 'r+') original_file.read() original

Solution 1:

original_file is a file object, you need to read it to get its contents, or the buffer that the regex requires.

Usually, it's also good that you use with (just so you don't have to remember closing the file), so you might end up with something like this:

import re

withopen('jokes.txt', 'r+') as original_file:
    contents = original_file.read()
    new_contents = re.sub(r"\d+\. ", "", contents)

You will see I rawed the regex string up there in the code (I used an r before the regex string). That's also a good practice, because sometimes you will have to double escape some characters for them to behave properly as you expect them.

Solution 2:

You call original_file.read(), but you don't assign that value to anything.

>>> original_file = open('test.txt', 'r+')
>>> original_file.read()
'Hello StackOverflow,\n\nThis is a test!\n\nRegards,\naj8uppal\n'>>> print original_file
<open file 'test.txt', mode 'r+' at 0x1004bd250>
>>> 

Therefore, you need to assign original_file = original_file.read():

import re
original_file = open('jokes.txt', 'r+')
original_file = original_file.read()
original_file = re.sub("\d+\. ", "", original_file)

I would also suggest using with like @Jerry, so that you don't have to close the file to save the writing.

Post a Comment for "Typeerror: Expected String Or Buffer | Python"