-3

So in my Python exercise I must write a program that computes and generates a report to a file with the charges for a patients hospital stay. The coding for the calculations were easy enough. Prompt user for info, calculate info, return total charges or whatever. My problem is with writing a report to the file including the charges entered by user and total amount for this charges. I've done everything perfect, I just don't really understand how writing to files and such works...

Infile=open("hospital_charges.txt","w")...

Now what? Yes obviously use the .write method. But my hospital charges file stays blank...

Muffen
  • 57
  • 1
  • 1
  • 6
  • 1
    https://docs.python.org/2/tutorial/inputoutput.html – khelwood Apr 06 '15 at 15:21
  • 2
    This has been answered here: [http://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file-in-python](http://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file-in-python) – Kyle Williamson Apr 06 '15 at 15:22

2 Answers2

0

using the write method

Infile.write("read documentation")

Documentation is here: https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

It is good practice to use the with keyword when dealing with file objects to automatically close the file after opening it to prevent nasty errors.All of which is documented in the link given above.

Always have a look at the related tab to the right before asking questions you would be surprised how often people have had the same doubt as us before !

solinvictus
  • 177
  • 1
  • 10
  • Very good answer! I heard that we need to close the file after performing writes, is this true? – vaultah Apr 06 '15 at 15:33
  • Yes of course we should close everything after using it , to prevent nasty errors in the future.You might have issues later on if you dont close the file and edit it in the mean while. – solinvictus Apr 06 '15 at 15:38
0

After writing to a file, you must close the file object to ensure data gets written to it, using

Infile.close()