0

I am trying to attempt something that I have not before within python.

The code below collects data from my test database and put it into a text under my headers of 'Test1','Test2','Test3'. This is working fine.

What I am trying to attempt now is to add a header (on top of the current header) and footer to the file.

python code:

file = 'file.txt'

header_names = {'t1':'Test1', 't2': 'Test2','t3':'Test3'}


with open(file, 'w', newline='') as f:
    w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='', extrasaction='ignore')
    w.writerow(header_names)
    for doc in res['test']['test']:
        my_dict = doc['test']



        w.writerow(my_dict)

current file output using the above code.

file.txt

Test1,Test2,Test3
Bob,john,Male
Cat,Long,female
Dog,Short,Male
Case,Fast,Male
Nice,who,Male

ideal txt output.

{header}
Filename:file.txt
date:

{data}
Test1,Test2,Test3
Bob,john,Male
Cat,Long,female
Dog,Short,Male
Case,Fast,Male
Nice,who,Male

{Footer}
this file was generated by using python.

the {header}, {data} and {footer} is not needed within the file that is just to make clear what is needed. i hope this makes sense.

R.Dave
  • 1
  • 4
  • Possible duplicate of [Correct way to write line to file?](https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file) – TrebledJ Mar 21 '19 at 12:57

2 Answers2

0

Something like this

import csv
from datetime import date

# prepare some sample data
data = [['Bob', 'John', 'Male'], 
        ['Cat', 'Long', 'Female']]
fieldnames = ['test1', 'test2', 'test3']
data = [dict(zip(fieldnames, row)) for row in data]

# actual part that writes to a file
with open('spam.txt', 'w', newline='') as f:
    f.write('filename:spam.txt\n')
    f.write(f'date:{date.today().strftime("%Y%m%d")}\n\n')
    wrtr = csv.DictWriter(f, fieldnames = fieldnames)
    wrtr.writeheader()
    wrtr.writerows(data)
    f.write('\nwritten with python\n')

Output in the file:

filename:spam.txt
date:20190321

test1,test2,test3
Bob,John,Male
Cat,Long,Female

written with python

Now, all that said, do you really need to write header and footer. It will just break a nicely formatted csv file and would require extra effort later on when reading it. Or if you prefer - is the csv format what best suits your needs? Maybe using json would be better...

buran
  • 13,682
  • 10
  • 36
  • 61
0
vardate= datetime.datetime.now().strftime("%x")
file = 'file.txt'
header_names = {'t1':'Test1', 't2': 'Test2','t3':'Test3'}
with open(file, 'w', newline='') as f:
    f.seek(0,0) //This will move cursor to start position of file
    f.writelines("File Name: ", file)
    f.writelines("date: ", vardate)
    f.writelines(".Try out next..")
    w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='', 
    extrasaction='ignore')
    w.writerow(header_names)
    for doc in res['test']['test']:
        my_dict = doc['test']
        w.writerow(my_dict)
    f.seek(0,2)
    f.writelines("This is generated using Python")
dhilip77
  • 11
  • 1