在文件内添加数据

时间:2019-03-21 12:47:44

标签: python python-3.x

我正在尝试使用python中以前没有的东西。

下面的代码从我的测试数据库中收集数据,并将其放在“ Test1”,“ Test2”,“ Test3”标题下的文本中。一切正常。

我现在试图尝试的是在文件中添加页眉(在当前页眉的顶部)和页脚。

python代码:

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)

使用上述代码输出当前文件。

file.txt

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

理想的txt输出。

{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.

文件中不需要{header},{data}和{footer}只是为了清楚需要什么。我希望这是有道理的。

2 个答案:

答案 0 :(得分:0)

类似这样的东西

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')

在文件中输出:

filename:spam.txt
date:20190321

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

written with python

现在,所有这些,您是否真的需要编写页眉和页脚。它只会破坏格式正确的csv文件,并且在以后读取它时将需要额外的精力。 或者,如果您愿意-csv格式最适合您的需求吗?也许使用json会更好...

答案 1 :(得分: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")