writing to file is just as easythe write method on file objects writes string (or bytesfor binary dataobject to the file it can be called repeatedly to write multiple stringsone after the other the writelines method accepts sequence of strings and writes each of the iterated values to the file the writelines method does not append new line after each item in the sequence it is basically poorly named convenience function to write the contents of sequence of strings without having to explicitly iterate over it using for loop lastlyand do mean lastlywe come to the close method this method should be called when we are finished reading or writing the fileto ensure any buffered writes are written to the diskthat the file has been properly cleaned upand that all resources associated with the file are released back to the operating system technicallythis will happen automatically when the script exitsbut it' better to be explicit and clean up after ourselvesespecially in long-running processes placing it in context the need to close files when we are finished with them can make our code quite ugly because an exception may occur at any time during file /owe ought to wrap all calls to file in try finally clause the file should be closed in the finally clauseregardless of whether / was successful this isn' very pythonic of coursethere is more elegant way to do it if we run dir on file-like objectwe see that it has two special methods named __enter__ and __exit__ these methods turn the file object into what is known as context manager basicallyif we use special syntax called the with statementthese methods will be called before and after nested code is executed on file objectsthe __exit__ method ensures the file is closedeven if an exception is raised we no longer have to explicitly manage the closing of the file here is what the with statement looks like in practicewith open('filename'as filefor line in fileprint(lineend=''the open call returns file objectwhich has __enter__ and __exit__ methods the returned object is assigned to the variable named file by the as clause we know the file will be closed when the code returns to the outer indentation leveland that this will happen even if an exception is raised