您可以使用字符串模板并离开
{}
将数据帧插入。整个事情变得更易读。有用的事情:1)使用
"""
对于多行字符串和2)使用注释来记住为什么要做某些事情。
import pandas as pd
df = pd.DataFrame({
"A": [1231, 1232, 1233, 1234],
"B": [1241, 1242, 1243, 1244],
"C": ['abc', 'abd', 'abe', 'abf']
})
# Setups the template that the client requested with 3-5 rows of information
# Followed by 3 blank rows and the dataframe
template = """\
some details
some more details
some details that were not covered in last two details
{}"""
with open('test.txt', 'w') as fp:
fp.write(template.format(df.to_csv(index=False)))
测试.csv:
some details
some more details
some details that were not covered in last two details
A,B,C
1231,1241,abc
1232,1242,abd
1233,1243,abe
1234,1244,abf
注:来自用户taras的数据