import math print('the value of pi is approximately % math pithe value of pi is approximately more information can be found in the old-string-formatting section reading and writing files open(returns file objectand is most commonly used with two argumentsopen(filenamemodef open('workfile'' 'the first argument is string containing the filename the second argument is another string containing few characters describing the way in which the file will be used mode can be 'rwhen the file will only be read'wfor only writing (an existing file with the same name will be erased)and 'aopens the file for appendingany data written to the file is automatically added to the end ' +opens the file for both reading and writing the mode argument is optional'rwill be assumed if it' omitted normallyfiles are opened in text modethat meansyou read and write strings from and to the filewhich are encoded in specific encoding if encoding is not specifiedthe default is platform dependent (see open()'bappended to the mode opens the file in binary modenow the data is read and written in the form of bytes objects this mode should be used for all files that don' contain text in text modethe default when reading is to convert platform-specific line endings (\ on unix\ \ on windowsto just \ when writing in text modethe default is to convert occurrences of \ back to platform-specific line endings this behind-the-scenes modification to file data is fine for text filesbut will corrupt binary data like that in jpeg or exe files be very careful to use binary mode when reading and writing such files it is good practice to use the with keyword when dealing with file objects the advantage is that the file is properly closed after its suite finisheseven if an exception is raised at some point using with is also much shorter than writing equivalent try-finally blockswith open('workfile'as fread_data read( closed true if you're not using the with keywordthen you should call close(to close the file and immediately free up any system resources used by it if you don' explicitly close filepython' garbage collector will eventually destroy the object and close the open file for youbut the file may stay open for while another risk is that different python implementations will do this clean-up at different times after file object is closedeither by with statement or by calling close()attempts to use the file object will automatically fail close( read(traceback (most recent call last)file ""line in valueerrori/ operation on closed file methods of file objects the rest of the examples in this section will assume that file object called has already been created reading and writing files