SamB SamB - 20 days ago 8
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:"))
print file.read()


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

Answer

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

file.close() 

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")
        file_to_write.write(content_of_file)
        # after that file_to_write.close() is called
    with open(name_of_file, 'r') as file_to_read:
        print(file_to_read.read())
        # after that file_to_read.close() is called