sam
sam

Reputation: 203

AttributeError: 'NoneType' object has no attribute 'read' in python

if __name__ == '__main__':
    filename = open('sevi.txt', 'wb')
    content = filename.write("Cats are smarter than dogs")
    for line in content.read(): 
        match = re.findall('[A-Z]+', line)
        print match
    filename.close()

I am new to python. I am just opening a file and writing some text into it. Later reading the content find all the characters in it by using regular expression. but I am getting the error as 'NoneType' object has no attribute 'read'. if I use readlines also, I am getting the error.

Upvotes: 0

Views: 5183

Answers (3)

yael
yael

Reputation: 337

import re 

ofile = open('sevi.txt', 'r+')

ofile.write("Cats are smarter than dogs")

ofile.seek(0)

data = ofile.read()

upper = re.findall(r'[A-Z]', data)

print upper

lower = re.findall(r'[a-z]', data)

print lower

ofile.close()

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124178

The file.write() method returns None in Python 2 (in Python 3 it returns the number of bytes written, for a binary file).

If you want to both write and read with the same file you'll need to open that file in w+ mode, and seek back to put the file position back to the start:

with open('sevi.txt', 'w+b') as fileobj:
    fileobj.write("Cats are smarter than dogs")
    fileobj.seek(0)  # move back to the start
    for line in fileobj: 
        match = re.findall('[A-Z]+', line)
        print match

Note that looping over the file object can be done directly, producing individual lines.

I made two other changes: I renamed your variable to fileobj; you have a file object, not just the name of the file here. And I used the file object as a context manager, so that it is closed automatically even if any errors occur in the block.

Upvotes: 6

Tony Babarino
Tony Babarino

Reputation: 3405

filename.write("Cats are smarter than dogs") is the function that returns None type like every function in Python if it's not specified otherwise with a return statement. So the value of the variable content is None and You are trying to read from that. Try filename.read() instead.

Upvotes: 0

Related Questions