我的代码将大量数据写入txt文件。 我正尝试将pandas dataframe 作为代码的一部分打印到该txt文件中,但无法使用.write()方法,因为它只接受字符串。
我该如何将一个名为DF1的pandas dataframe打印到文件中?
我看到了类似的问题,但那些问题是针对仅为dataframe创建txt文件的,而我只希望我的dataframe出现在txt文件中。
我的代码将大量数据写入txt文件。 我正尝试将pandas dataframe 作为代码的一部分打印到该txt文件中,但无法使用.write()方法,因为它只接受字符串。
我该如何将一个名为DF1的pandas dataframe打印到文件中?
我看到了类似的问题,但那些问题是针对仅为dataframe创建txt文件的,而我只希望我的dataframe出现在txt文件中。
使用to_string
方法,然后您可以将模式设置为'a'
,使用write
方法进行追加写入。
tfile = open('test.txt', 'a')
tfile.write(df.to_string())
tfile.close()
示例数据
import pandas as pd
import numpy as np
df = pd.DataFrame({'id': np.arange(1,6,1),
'val': list('ABCDE')})
test.txt
This line of text was here before.
代码
tfile = open('test.txt', 'a')
tfile.write(df.to_string())
tfile.close()
This line of text was here before.
id val
0 1 A
1 2 B
2 3 C
3 4 D
4 5 E
to_string()
、to_json()
和to_csv()
方法,这些方法可以帮助你。详见:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_string.html、https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html、https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_json.html。example_string = df1.to_string()
output_file = open('file.txt','a')
output_file.write(example_string)
output_file.close()
import json
filename = 'file.json'
with open(filename, 'w') as file:
json.dump(df1.to_json(), file)