2022年 11月 5日

Python保存数据到文件的方法

方法一:open函数保存

#保存数据open函数
with open('D:/PythonWorkSpace/TestData/pinglun.txt','w',encoding='utf-8') as f:#使用with open()新建对象f
    for i in comments:
        print(i)
        f.write(i+'\n')#写入数据,文件保存在上面指定的目录,加\n为了换行更方便阅读  

方法二: numpy

#导入包import pandas as pd
import numpy as np
 
df = pd.DataFrame(np.random.randn(10,4))#创建随机值
 
#print(df.head(2))#查看数据框的头部数据,默认不写为前5行,小于5行时全部显示;也可以自定义查看几行
print(df.tail())##查看数据框的尾部数据,默认不写为倒数5行,小于5行时全部显示;也可以自定义查看倒数几行
 
df.to_csv('D:/PythonWorkSpace/TestData/PandasNumpy.csv')#存储到CSV中
#df.to_excel('D:/PythonWorkSpace/TestData/PandasNumpy.xlsx')#存储到Excel中(需要提前导入库 pip install openpyxl)

方法三:csv写入

import csv
import codecs
with codecs.open('./test.csv', 'w', 'utf-8') as csvfile:
    # 指定 csv 文件的头部显示项
    filednames = ['ID', 'PRICE']
    writer = csv.DictWriter(csvfile, fieldnames=filednames)
    writer.writeheader()
    for i in range(0, len(test_index)):
        try:
            writer.writerow({'ID':test_index[i], 'PRICE':y_pred[i]})
        except UnicodeEncodeError:
            print("编码错误, 该数据无法写到文件中, 直接忽略该数据")

方法四:DataFrame

可能的问题:csv文件中看不到数据,但是通过python代码可以看到数据

dataframe = pd.DataFrame({'ID':test_index,'PRICE': y_pred})
# dataframe = pd.DataFrame({'PRICE': test_index})
dataframe.to_csv("test12.csv",index=False,sep='\n')

方法五
import codecs #或者io,使用哪种包无所谓
with codecs.open('your_file.txt', 'r', 'utf-8') as f:
    f.write('This method is prior')

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49