writing files open directory window for your python program directory first note that there is no file named sample txt make sure you have started idle so the current directory is your python program directory run the example program firstfile pyshown belowoutfile open('sample txt'' 'outfile write('my first output file!'outfile close(the first line creates file objectwhich links python to your computer' file system the first parameter in the file constructor gives the file namesample txt the second parameter indicates how you use the file the 'wis short for writeso you will be creating and writing to file warningif the file already existedthe old contents are destroyed if you do not use any operating system directory separators in the name ('\or '/depending on your operating system)then the file will lie in the current directory the assignment statement gives the python file object the name outfile the second line writes the specified string to the file the last line is important to clean up until this linethis python program controls the fileand nothing may be actually written to an operating system file yetsince initiating file operation is thousands of times slower than memory operationspython buffers datasaving small amounts and writing larger chunk all at once warningthe close line is essential for python to make sure everything is really writtenand to relinquish control of the file it is common bug to write program where you have the code to add all the data you want to filebut the program does not end up creating file usually this means you forgot to close the file now switch focus and look at directory window for the current directory you should now see file sample txt you can open it in idle (or your favorite word processorand see its contents for the next examplerun the example program nextfile pyshown belowwhich has two calls to the write methodoutfile open('sample txt'' 'outfile write('my second output file!'outfile write('write some more 'outfile close(now look at the filesample txt open it in idle it may not be what you expectthe write method for the file is not quite like print function it does not add anything to the file except exactly the data you tell it to write if you want newlineyou must indicate it explicitly recall the newline code '\nrun the example program revisedfile pyshown belowwhich adds newline codesoutfile open('sample txt'' 'outfile write(' revised output file!\ 'outfile write('write some more \ 'outfile close(check the contents of sample txt files