After_Sunset
After_Sunset

Reputation: 714

How to write text to an output file in a structured, organize manner

I'm am trying to to write user input to a .txt file. The code i currently have looks like this:

with open('Emp schedule.txt','w') as schedule:
   schedule.write(get_name + "\n"  + str(get_pay_rate) + "\n" + str(get_the_hours))

This code just over-writes the previous data every time it is ran. How can i write data to this file without over-writing anything and also do it in a orderly manner with some sort of parameters that i set? Also, any good articles or webpages with information on writing text to a file is appreciated. I've read the python docs already.

Upvotes: 0

Views: 1397

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

with open('Emp schedule.txt','a') as schedule:

Use a to append to the file.

Or a+ to open for reading and writing.

You can use str.format to write to your file:

with open('Emp schedule.txt','a') as schedule:
   schedule.write("{}\n{}\n{}\n".format(get_name,get_pay_rate,get_the_hours))

If you have a dict you can use the ** syntax:

pay_dict = {"get_name": "foo","get_pay_rate" : 50,"get_the_hours": 40}

with open('Emp schedule.txt','a') as schedule:
   schedule.write("{get_name}\n{get_pay_rate}\n{get_the_hours}\n".format(**pay_dict))

I am not a csv pro but this will write to a file with the fields delimited by whatever you specify and writes the rows based on the dict key values of the headers using the csv module:

d = {"Name": "foo","Pay_date" : 50,"Hours": 40}

import csv
with open('Emp schedule.csv','a') as schedule:
   writer= csv.DictWriter(schedule,d,delimiter ="|")
   writer.writeheader() # write header
   writer.writerow(d) # write values
#

Upvotes: 3

Related Questions