# File_IO_Demo_Write_to_File.py # # Anne Lavergne # July 2015 - Modified July 2017 # # Either ask user for a filename (and perhaps also a path) # OR # set your filename variables once at the top of your program # Why? outputFile = "newFile.txt" # Open file for writing fileW = open(outputFile, 'w') # Must first convert everything to a string before writing it to a file. # To do so, we can use the string conversion built-in function str() value = [3, 1, 4, 1, 5, 1, 6, 1] aString = str(value) + "\n" numOfChars1 = fileW.write(aString) # write() method returns the number of characters written to the file print("Writing:\n{0}to the file '{1}'.".format(aString, outputFile)) print("Number of characters written is {}.\n".format(numOfChars1)) # or we can use string .format() method aString = "The answer is" aFloat = 3.14159265359 anInt = 42 myData = " {0} and perhaps {1:0.2f}.\n".format(anInt, aFloat) numOfChars2 = fileW.write(aString+myData) print("Writing:\n{0}to the file '{1}'.".format(aString+myData, outputFile)) print("Number of characters written is {}.\n".format(numOfChars2)) print("For a total number of {} characters written.".format(numOfChars1+numOfChars2)) # It is good programming style to always close a opened file fileW.close( )