Python 如何在写入数据帧之前向csv添加详细信息

Python 如何在写入数据帧之前向csv添加详细信息,python,pandas,export-to-csv,Python,Pandas,Export To Csv,我需要写入一个csv文件,该文件有3-5行(行)关于该文件的详细信息,然后是3行空行,然后才能附加到数据帧 下面是文件的外观。(注意:带有“#”的行是用于演示的注释) 以下是我到目前为止所做的尝试: import pandas as pd file_name = 'my_csv_file.csv' df1 = pd.Dataframe({"some details":}) df2 = pd.DataFrame({"some more details":}) df3 = pd.DataFram

我需要写入一个csv文件,该文件有3-5行(行)关于该文件的详细信息,然后是3行空行,然后才能附加到数据帧

下面是文件的外观。(注意:带有“#”的行是用于演示的注释)

以下是我到目前为止所做的尝试:

import pandas as pd

file_name = 'my_csv_file.csv'

df1 = pd.Dataframe({"some details":})
df2 = pd.DataFrame({"some more details":})
df3 = pd.DataFrame({"some details that were not covered in last two details'})
df4 = pd.DataFrame({"\n\n\n\":}) #write 3 blank lines
df5 = pd.DataFrame({"A":[1231 1232 1233 1234]
                    "B":[1241 1242 1243 1244]
                   "headers":[abc abd abe abf] }

df1.to_csv(file_name, sep=';', mode='a', index=False)
df2.to_csv(file_name, sep=';', mode='a', index=False)
df3.to_csv(file_name, sep=';', mode='a', index=False)
df4.to_csv(file_name, sep=';', mode='a', index=False)
df5.to_csv(file_name, sep=';', mode='a', index=False)

但这似乎不起作用。有人能帮我吗?

你可以使用一个字符串模板,然后离开
{}
将数据帧插入。整个故事变得更具可读性。有用的操作: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)))
test.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的数据

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