view raw
SamB SamB - 6 months ago 28
Python Question

Why am I getting a AttributeError: 'NoneType' object has no attribute 'read'?

print "Enter the name of the file",
file= open(raw_input(":"),'w').write(raw_input("Enter the content:"))

In response I am getting
AttributeError: 'NoneType' object has no attribute 'read'
. Please can anyone help.


write() method doesn't return anything, so file value is None.

You should assign result of open() function to file variable and secondly call write method on it.

If you are using:

open(path_to_file, 'w') 

you can read content of this file.

And when you call

file = open(some options) 

method you should call


after end of file processing.

But in python has with keyword which (for instance of file class) call close() method automatically after end of code block execution, even if an exception occurced. So your method can be implemented like this:

def write_to_file_and_print_content():
    print("Enter the name of the file:")
    name_of_file = raw_input("")
    # Writting to file
    with open(name_of_file, 'w') as file_to_write:
        content_of_file = raw_input("Enter the content:\n")
        # after that file_to_write.close() is called
    with open(name_of_file, 'r') as file_to_read:
        # after that file_to_read.close() is called