Article Directory
1. Python built-in method
Reading files (read(), readline(), readlines())
method | describe |
---|---|
read() | Read the entire file content at once. |
readline() | Read one line at a time. Used when the memory is not enough, generally not used |
readlines() | Read the entire file content at one time, and return to the list line by line, which is convenient for us to traverse |
- read()
scores.txt
Ron 23 35 44
Harry 60 77 68 88 90
Hermione 97 99 89 91 95 90
Malfoy 100 85 90
file1 = open('F:\\python_test\\scores.txt','r',encoding='utf-8') # \在Python中是转义字符,所以时常会有冲突。为了避坑,Windows的绝对路径通常要稍作处理,写成以下两种格式; 'F:\\python_test\\scores.txt' 或者 r'F:\python_test\scores.txt'
file_read = file1.read()
file1.close()
print(file_read)
operation result
罗恩 23 35 44
哈利 60 77 68 88 90
赫敏 97 99 89 91 95 99
马尔福 100 85 90
- readlines()
readlines() will get a list from the txt file, and each string in the list is each line in scores.txt. And there is a newline \n symbol after each string .
file1 = open('F:\\python_test\\scores.txt','r',encoding='utf-8')
file_lines = file1.readlines()
file1.close()
print(file_lines)
operation result
['罗恩 23 35 44\n', '哈利 60 77 68 88 90\n', '赫敏 97 99 89 91 95 99\n', '马尔福 100 85 90']
Write to file (write(), writelines())
method | describe |
---|---|
write() | Parameter must be of type string |
writelines() | The parameter can be a list (sequence) type |
- write()
If the open file mode contains w (write), then when writing content to the file, the content in the original file will be cleared first, and then new content will be written.
file1 = open('F:\\python_test\\abc.txt','w',encoding='utf-8')
file1.write('张无忌\n')
file1.write('宋青书\n')
file1.close()
So run the above program and open the abc.txt file again, only the newly written content will be seen:
- append to file
If you just want to add something, but don't want to completely overwrite the original file, use the 'a' mode, which means append. Newly written content will be added behind the original content.
file1 = open('F:\\python_test\\abc.txt','a',encoding='utf-8')
file1.write('张无忌\n')
file1.write('宋青书\n')
file1.close()
Run the program, open the abc.txt file, you can see the following content
- writelines()
file1 = open('F:\\python_test\\scores.txt','r',encoding='utf-8')
file2=open('F:\\python_test\\scores_writelines.txt','w+',encoding='utf-8')
file2.writelines(file1.readlines())
file1.close()
file2.close()
Run the program, open the scores_writelines.txt file, you can see the following content
Note: When using the writelines() function to write multiple lines of data to a file, newlines will not be automatically added to each line. In the above example, the reason why the scores_writelines.txt file displays data line by line is because the readlines() function reads the newline character at the end of the line when reading each line of data.
2. Python module (built-in module csv, external module openpyxl)
csv module write and read
- csv write file steps
1. Create a file: call the open() function
2. Create an object: use the writer() function
3. Write content: call the writerow() method of the writer object
4. Close the file: close()
import csv #导入csv模块
csv_file = open('F:\\python_test\\demo.csv','w',newline='',encoding='utf-8') # 调用open()函数打开csv文件,传入参数:文件名“demo.csv”、写入模式“w”、newline=''、encoding='utf-8'。
writer = csv.writer(csv_file) # 用csv.writer()函数创建一个writer对象。
writer.writerow('\ufeff')#解决使用excel打开时中文字符出现乱码情况
writer.writerow(['电影','豆瓣评分']) # 调用writer对象的writerow()方法,可以在csv文件里写入一行文字 “电影”和“豆瓣评分”。
writer.writerow(['银河护卫队','8.0'])
writer.writerow(['复仇者联盟','8.1'])
csv_file.close() # 写入完成后,关闭文件
- csv read file steps
1. Open the file: call the open() function
2. Create an object: use the reader() function
3. Read the content: traverse the reader object
4. Print the content: print()
import csv
csv_file=open('F:\\python_test\\demo.csv','r',newline='',encoding='utf-8') #用open()打开“demo.csv”文件,'r'是read读取模式,newline=''是避免出现两倍行距。encoding='utf-8'能避免编码问题导致的报错或乱码
reader=csv.reader(csv_file) #用csv.reader()函数创建一个reader对象
for row in reader: #用for循环遍历reader对象的每一行。打印row,就能读取出“demo.csv”文件里的内容
print(row)
csv_file.close()
operation result
Module openpyxl writes and reads
- Excel file writing steps
1. Create a workbook: use openpyxl.Workbook{} to create a workbook object
2. Get a worksheet: use the active attribute of the workbook object
3. Operate cells: cell: sheet['A1']; row: append()
4. Save workbook: save{}
import openpyxl # 导入openpyxl
wb=openpyxl.Workbook() # 利用openpyxl.Workbook()函数创建新的workbook(工作簿)对象,就是创建新的空的Excel文件。
sheet=wb.active # wb.active就是获取这个工作簿的活动表,通常就是第一个工作表。
sheet.title='册页一与一' # 可以用.title给工作表重命名。现在第一个工作表的名称就会由原来默认的“sheet1”改为"new title"。
sheet['A1'] = '吴青峰' # 把'漫威宇宙'赋值给第一个工作表的A1单元格,就是往A1的单元格中写入了'漫威宇宙'。
rows = [['费洛蒙小姐','我会我会','最难的是相遇','低低星垂'],['宁静海','困在','迷幻','极光']] # 先把要写入的多行内容写成列表,再放进大列表里,赋值给rows。
for i in rows: # 遍历rows,同时把遍历的内容添加到表格里,这样就实现了多行写入。
sheet.append(i)
print(rows)
wb.save('F:\\python_test\\song.xlsx') # 保存新建的Excel文件,并命名为“song.xlsx”
Run the program and view the song.xlsx file
- Excel file reading steps
1. Open the workbook: use openpyxl.Workbook{} to create a workbook object
2. Get the worksheet: use the active attribute of the workbook object
3. Read the cell: cell: sheet['A1']; row: append()
4 , print cell: save{}
wb = openpyxl.load_workbook('F:\\python_test\\song.xlsx') #调用openpyxl.load_workbook()函数,打开“song.xlsx”文件。
sheet = wb['册页一与一']#获取“song.xlsx”工作簿中名为“册页一与一”的工作表。
sheetname = wb.sheetnames#sheetnames是用来获取工作簿所有工作表的名字的。
print(sheetname) #如果你不知道工作簿到底有几个工作表,就可以把工作表的名字都打印出来。
A1_cell = sheet['A1'] #把“册页一与一”工作表中A1单元格赋值给A1_cell,再利用单元格value属性,就能打印出A1单元格的值。
A1_value = A1_cell.value
print(A1_value)
operation result
3. Use the pandas library
Write to file (.csv, .excel, .txt, etc.)
The method of writing to a file using pandas is as follows:
method | describe | return data |
---|---|---|
to_csv() | Write to .csv format or .txt format file | output dataframe format |
to_excel() | Write excel files (including xlsx, xls, xlsm formats) | output dataframe format |
- Write to .csv file: to_csv()
import pandas as pd
pd.to_csv() is a method of the DataFrame class
- Basic parameters
DataFrame.to_csv(path_or_buf=None, sep=‘,’, na_rep=‘’, float_format=None, columns=None, header=True, index=True, index_label=None, mode=‘w’, encoding=None, compression=‘infer’, quoting=None, quotechar=‘"’, line_terminator=None, chunksize=None, date_format=None, doublequote=True, escapechar=None, decimal=‘.’, errors=‘strict’)
parameter name | function and meaning |
---|---|
path_or_buf | file output path |
sep | delimiter, default is ',' |
and_rep | Missing data filling, the default is an empty string |
float_format | String format, how many decimal places are reserved |
columns | Column names to output to csv |
header | Whether to keep the column name, the default is to keep the column name, you can pass in a list of column names list |
index | write row name (index), default write |
encoding | Encoding format, indicating the encoding string used in the output file, Python2 defaults to "ASCII", and Python3 defaults to "UTF-8". |
- path_or_buf path
#任意的多组列表
a = [1,2,3]
b = [4,5,6]
#字典中的key值即为csv中列名
dataframe = pd.DataFrame({
'a_name':a,'b_name':b})
#将DataFrame存储为csv,index表示是否显示行名
dataframe.to_csv("F:\\python_test\\test.csv",index=False,sep=',')
operation result
import pandas as pd
data_read_path='F:\\python_test\\demo.csv'
data_write_path='F:\\python_test\\demo_save.csv' #指明保存文件路径
data=pd.read_csv(data_read_path)
data.to_csv(data_write_path,index=False,encoding='utf=8-sig')
operation result
- sep separator
data.to_csv(data_write_path,sep=',')
- np_rep
data.to_csv(data_write_path,sep=',',na_rep="NULL",encoding='utf=8-sig') #空值保存为NULL,如果不写,默认是空
operation result
- float_format
data.to_csv(data_write_path,float_format='%.2f',encoding='utf=8-sig') #保留两位小数
operation result
- columns
data.to_csv(data_write_path,columns=['电影'],encoding='utf=8-sig') #只保留名为“电影”这一列
operation result
- header
data.to_csv(data_write_path,header=0,encoding='utf=8-sig') #不保存列名
operation result
- index
data.to_csv(data_write_path,index=0,encoding='utf=8-sig') #不保存行索引
operation result
- Write to .txt file: to_csv()
import pandas as pd
pd.to_csv()
Remember to set the segmentation method: sep
import pandas as pd
data_read_path='F:\\python_test\\demo.csv'
data=pd.read_csv(data_read_path)
data.to_csv('F:\\python_test\\demo_save.txt', sep='\t', index=False)
operation result
- Write to .excel file: to_excel()
import pandas as pd
pd.to_excel()
- Basic parameters
DataFrame.to_excel(excel_writer, sheet_name=‘Sheet1’, na_rep=‘’, float_format=None, columns=None,
header=True, index=True, index_label=None, startrow=0, startcol=0, engine=None, merge_cells=True,
encoding=None, inf_rep=‘inf’, verbose=True, freeze_panes=None)
parameter name | function and meaning |
---|---|
excel_writer | file path or existing ExcelWriter |
sheet_name | It refers to the name of the worksheet containing the DataFrame. |
The meanings of other parameters are similar to to_csv(), please refer to the previous to_csv() example.
- Single sheet write
import pandas as pd
df1 = pd.DataFrame({
'One': [1, 2, 3]})
df1.to_excel('F:\\python_test\\excel1.xlsx', sheet_name='test1', index=False) # index false为不写入索引
operation result
Read files (.csv, .excel, .txt, etc.)
The method of reading files using pandas is as follows:
method | describe | return data |
---|---|---|
read_csv() | Read csv format file | output dataframe format |
read_excel() | Read excel files (including xlsx, xls, xlsm formats) | output dataframe format |
read_table() | Read txt files, and read any text files through the control of the sep parameter (delimiter) | |
read_json() | Read json format file | |
read_html() | read html form | |
read_clipboard() | read clipboard content | |
read_pickle() | Read pickled persistent files | |
read_sql() | Read the database data, and after connecting to the database, just pass in the sql statement. | |
read_dhf() | Read hdf5 files, suitable for reading large files. | |
read_parquet() | read parquet file | |
read_sas() | read sas file | |
read_stata() | read stata file | |
read_gdp() | Read google_blgquery data |
- Read .csv files: read_csv()
pandas.read_csv(filepath_or_buffer, sep=, delimiter=None, header=‘infer’, names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression=‘infer’, thousands=None, decimal=’.’, lineterminator=None, quotechar=’"’, quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, dialect=None, error_bad_lines=True, warn_bad_lines=True, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None, storage_options=None)
- 基本参数
参数名称 | 功能以及含义 |
---|---|
filepath_or_buffer | 可以是文件路径、可以是URL,也可以是实现read方法的任意对象。 |
sep | 字符串,表示分隔符,默认为’,’ .。 |
delimiter | 分隔符的另一个名字,与sep功能相似,默认None。 |
delim_whitespace | 默认为False,设置为True时,表示分隔符这空白字符,可以是空格,‘\t’等等。不管分隔符是什么,只要是空白字符,那么可以通过delim_whitespace=True进行读取。 |
header | 设置导入DataFrame的列名称,默认为”infer“,注意它与下面介绍的names参数的微妙关系。 |
names | 当names没被赋值时,header=0,即选取数据文件的第一行作为列名;当names被赋值,header没被赋值时,header=None。如果都赋值,就会实现两个参数的组合功能。 |
index_col | 读取文件之后得到的DataFrame的索引默认是0,1,2…,我们可以通过set_index设定索引,但是也可以在读取的时候就指定某列为索引。 |
usecols | 如果一个数据集中含有很多列,但是我们在读取的进修只想要使用到的列,就可以使用这个参数。 |
mangle_dupe_cols | 在实际工作中,我们得到的数据会很复杂,有时导入的数据会含有名字相同的列。参数 mangle_dupe_cols 会将重名的列后面多一个 .1,该参数默认为 True,如果设置为 False,会抛出不支持的异常。 |
prefix | 当导入的数据没有header时,设置此参数会自动加一个前缀。 |
- filepath_or_buffer
import pandas as pd
data_path='F:\\python_test\\demo.csv'
data=pd.read_csv(data_path)
print(data)
运行结果
- sep
从图中,得知 demo.csv 的分隔符为 ‘,’
注意:“csv文件的分隔符” 和 “我们读取csv文件时指定的分隔符” 一定要一致。 不一致,因此多个列之间没有分开,而是连在一起了,如下图所示。 所以,我们需要将分隔符设置成 ‘,’ 才可以。
pd.read_csv(data_path,sep='\t')
运行结果
pd.read_csv(data_path,sep=',')
运行结果
- delim_whitespace :不管分隔符是什么,只要是空白字符,那么可以通过delim_whitespace=True进行读取。
pd.read_csv(data_path,delim_whitespace=True)
运行结果
- header、names
1、 csv文件有表头并且是第一行,那么names和header都无需指定;
2、csv文件有表头、但表头不是第一行,可能从下面几行开始才是真正的表头和数据,这个时候指定header即可;
3、csv文件没有表头,全部是纯数据,那么我们可以通过names手动生成表头;
4、csv文件有表头、但是这个表头你不想用,这个时候同时指定names和header。先用header选出表头和数据,然后再用names将表头替换掉,就等价于将数据读取进来之后再对列名进行rename;
1)names 没有被赋值,header 也没赋值:
#header=0,即选取文件的第一行作为表头
pd.read_csv(data_path,sep=',')
运行结果
2)names 没有被赋值,header 被赋值:
#不指定names,指定header为1,则选取第二行当做表头,第二行下面为数据。
pd.read_csv(data_path,sep=',',header=1)
运行结果
3)names 被赋值,header 没有被赋值:
pd.read_csv(data_path,sep=',',names=['id','movies','grades','date'])
运行结果
4)names 和 header 都被赋值:
#相当于先不看names,只看header,header为0代表先把第一行当做表头,下面的当成数据;然后再把表头用names给替换掉。
pd.read_csv(data_path,sep=',',names=['id','movies','grades','date'],header=0)
运行结果
- index_col:我们在读取文件之后所得到的DataFrame的索引默认是0、1、2……,我们可以通过set_index设定索引,但是也可以在读取的时候就指定某列为索引。
pd.read_csv(data_path,sep=',',index_col="电影")
运行结果
- usecols:如果一个数据集中有很多列,但是我们在读取的时候只想要使用到的列,我们就可以使用这个参数。
pd.read_csv(data_path,sep=',',usecols=["电影"])
运行结果
- prefix :当导入的数据没有 header 时,设置此参数会自动加一个前缀。
pd.read_csv(data_path,sep=',', header=None, prefix="hello")
运行结果
- 通用解析参数
参数名称 | 功能以及含义 |
---|---|
dtype | 在读取数据的时候,设定字段的类型。 |
engine | pandas解析数据时用的引擎,目前解析引擎有两种:c、python。默认为 c,因为 c 引擎解析速度更快,但是特性没有 python 引擎全。如果使用 c 引擎没有的特性时,会自动退化为 python 引擎。 |
converters | 读取数据的时候对列数据进行变换。 |
skiprows | 表示过滤行,想过滤哪些行,就写在一个列表里面传递给skiprows即可。 |
skipfooter | 从文件末尾未过滤行。 |
nrows | 设置一次性读入的文件行数。 |
comment | 指定注释符,在读取数据时,如果碰到行首指定的注释符,则跳过该行。 |
- dtype:
例如,编号为“0002”,如果默认读取的时候,会显示为2,所以这个时候要把他转为字符串类型,才能正常显示为0002:
pd.read_csv(data_path,sep=',')
运行结果
pd.read_csv(data_path,sep=',',dtype={
"编号": str})
运行结果
- converters:
例如将编号增加10,在使用converters参数时,解析器默认所有列的类型为str,所以需要进行类型转换。
pd.read_csv(data_path,sep=',',converters={
"编号": lambda x: int(x) + 10})
运行结果
- skiprows:
这里把第一行过滤掉了,因为第一行是表头,所以在过滤掉之后第二行就变成表头了。
注意的是:这里是先过滤,然后再确定表头。
pd.read_csv(data_path, sep=",", skiprows=[0])
运行结果
当然里面除了传入具体的数值,来表明要过滤掉哪些行,还可以传入一个函数。
由于索引从0开始,所以凡是索引大于0、并且%2等于0的记录都过滤掉。索引大于0,是为了保证表头不被过滤掉。
pd.read_csv(data_path, sep=",", skiprows=lambda x:x>0 and x%2 == 0)
运行结果
- skipfooter:从文件末尾过滤行,解析引擎退化为 Python。这是因为 C 解析引擎没有这个特性。
pd.read_csv(data_path, sep=",", skipfooter=3, encoding="utf-8", engine="python")
运行结果
- nrows:设置一次性读入的文件行数。
pd.read_csv(data_path, sep=",", nrows=1)
运行结果
- 空值处理相关参数
参数名称 | 功能以及含义 |
---|---|
na_values | 该参数可以配置哪些值需要处理成NaN |
- na_values
pd.read_csv(data_path, sep=",", na_values={
"电影": ["银河护卫队", "复仇者联盟"]})
运行结果
- 时间处理相关参数
参数名称 | 功能以及含义 |
---|---|
parse_dates | 指定某些列为时间类型,这个参数一般搭配date_parse使用。 |
date_parser | 用来配合parse_dates参数的,因为有的列虽然是日期,但没办法直接转化,需要我们指定一个解析格式。 |
infer_datetime_format | 参数默认为 False。如果设定为 True 并且 parse_dates 可用,那么 pandas 将尝试转换为日期类型,如果可以转换,转换方法并解析,在某些情况下会快 5~10 倍。 |
from datetime import datetime
data_1=pd.read_csv(data_path,sep=',')
data_2=pd.read_csv(data_path, sep=",", parse_dates=["日期"], date_parser=lambda x: datetime.strptime(x, "%Y-%m-%d"))
print(data_1.dtypes)
运行结果
print(data_2.dtypes)
运行结果
- 读取 .excel 文件:read_excel()
pandas.read_excel(io,sheet_name=0,
header=0,names=None,index_col=None,usecols=None,squeeze=False,dtype=None,engine=None,converters=None,true_values=None,false_values=None,skiprows=None,nrows=None,na_values=None,keep_default_na=True,verbose=False,parse_dates=False,date_parser=None,thousands=None,comment=None,skipfooter=0,convert_float=True,mangle_dupe_cols=True,**kwds)
- io:支持str,bytes,ExcelFile, xlrd.Book, path object, or file-like object。
默认读取第一个sheet的全部数据
import pandas as pd
excel_path='F:\\python_test\\song.xlsx'
pd.read_excel(excel_path)
运行结果
- sheet_name():参数支持str,int,list,None,default()格式
str字符串用于引用的sheet的名称
pd.read_excel(excel_path,sheet_name=“无与伦比的美丽”)
运行结果
int整数用于引用的sheet的索引(从0开始)
pd.read_excel(excel_path,sheet_name=2,names=["song"],header=None)
运行结果
字符串或整数组成的列表用于引用特定的sheet
读取后的数据类型是OrderedDict,将两个sheet的数据合并到了一个list中
pd.read_excel(excel_path,sheet_name=[2,"无与伦比的美丽"],names=["song"],header=None)
运行结果
None 表示引用所有sheet
pd.read_excel(excel_path,sheet_name=None)
运行结果
- 其他参数与read_csv()相似,可以参考前面讲解结合使用。
读取 .txt 文件:read_table()
pandas.read_table(filepath_or_buffer, *, sep=_NoDefault.no_default, delimiter=None, header=‘infer’, names=_NoDefault.no_default, index_col=None, usecols=None, squeeze=None, prefix=_NoDefault.no_default, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, skipfooter=0, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, cache_dates=True, iterator=False, chunksize=None, compression=‘infer’, thousands=None, decimal=‘.’, lineterminator=None, quotechar=‘"’, quoting=0, doublequote=True, escapechar=None, comment=None, encoding=None, encoding_errors=‘strict’, dialect=None, error_bad_lines=None, warn_bad_lines=None, on_bad_lines=None, delim_whitespace=False, low_memory=True, memory_map=False, float_precision=None, storage_options=None)
有一个test.txt文件,内容如下:
import pandas as pd
#用read_table函数读取文本文件的数据
data=pd.read_table('F:\\python_test\\test.txt', #文件路径,前面的filepath_or_buffer符可以省略掉
sep=',',#指定数据中变量之间的分隔符,注意这里是中文的逗号
header=None , #不需要将原来的数据中的第一行读作表头
names=['id','name','gender','native place'] , #重新为各列起变量名称
converters={
'id':str} ,#将ID转换为字符串,以免开头的00消失
skiprows=2 , #跳过开头的两行数据
skipfooter=2, #跳过末尾的两行数据
comment='!', #不读取“!”开头的数据行
engine='python',#skipfooter:从文件末尾过滤行,解析引擎退化为 Python,C 解析引擎没有这个特性。
encoding='utf-8' #为防止中文乱码
)
运行结果
三、使用numpy库
写入文件(savetxt()、save()、savez())
Numpy写入文件的3中方法:savetxt()、save()、savez()。
方法 | 描述 | 返回数据 |
---|---|---|
savetxt() | 将1维或者2维数组写入txt文本或csv文件 | 数组 |
save() | 写Numpy专用的二进制数据,将数组以未压缩二进制格式保存在扩展名为.npy的文件中。会自动处理元素类型和形状等信息。 | |
savez() | 写Numpy专用的二进制格式文件。将多个数组压缩到一个扩展名为npz的文件。其中每个文件都是一个save()保存的npy文件。 | 数据 |
- savetxt()
numpy.savetxt(fname,array,fmt=‘%.18e’,delimiter=None,newline=‘\n’, header=‘’, footer=‘’, comments='# ', encoding=None)**
- 主要参数
参数名称 | 功能以及含义 |
---|---|
fname | 文件、字符串或产生器,可以是.gz或.bz2的压缩文件。 |
array | 存入文件的数组(一维数组或者二维数组) |
fmt | 写入文件的格式,如%d , %.2f , %.18e,默认值是%.18e(浮点数)。 |
delimiter | 分隔符,通常情况是str可选。 |
header | 将在文件开关写入的字符串。 |
footer | 将在文件尾部写入的字符串。 |
comments | 将附加到header和footer字符串的字符串,以将其标记为注释。默认值:’#’ |
encodiing | 用于编码输出文件的编码。 |
- 写入 .txt 文件
import numpy as np
arr=np.arrange(12).reshape(3,4)
## 保存为txt文件,fmt缺省取%.18e(浮点数),分割符默认是空格。
np.savetxt("F:\\python_test\\numpy_test_1.txt",arr)
运行结果
## fmt:%d 写入文件的元素是十进制整数,分割符为逗号","。
np.savetxt("F:\\python_test\\numpy_test_2.txt",arr,fmt="%d",delimiter=',')
运行结果
## 在numpy_test_3.txt文件头部和尾部增加注释,头部 #test_3,尾部 # 数据写入注释,写入文件的元素是字符串
np.savetxt("F:\\python_test\\numpy_test_3.txt",arr,fmt="%s",delimiter=',',header=\
'test_3',footer="测试数据",encoding="utf-8")
运行结果
## 在numpy_test_4.txt文件头部加 ##test_4 注释
np.savetxt("F:\\python_test\\numpy_test_4.txt",arr,fmt="%f",delimiter=',',header='test_4',footer="测试数据",encoding="utf-8")
运行结果
- 写入 .csv 文件
## 将保存为csv文件
np.savetxt("F:\\python_test\\numpy_test_2.csv",arr,fmt='%d',header='test_2',delimiter=',')
运行结果
- save()
numpy.save(file,array)
- savez()
numpy.savez(file,array)
读取文件(loadtxt()、load()、fromfile())
Numpy读取文件的3中方法:loadtxt()、load()、fromfile()。
方法 | 描述 | 返回数据 |
---|---|---|
loadtxt() | 读取txt文本、csv文件以及.gz 或.bz2格式压缩文件,前提是文件数据每一行必须要有数量相同的值。 | 数组 |
load() | 读取Numpy专用的二进制数据,读取从npy、npz、pickle文件加载数组或pickled对象 | 数组、元组、字典等 |
fromfile() | 简单的文本、二进制数 | 数据 |
- laodtxt()
numpy.loadtxt(fname,dtype=type’float’>,comments=’#’,delimiter=None, converters=None,skiprows=0,usecols=None,unpack=False,ndmin=0,encoding=‘bytes’)
- 基本参数
方法 | |
---|---|
fname | 文件的相对地址或者绝对地址(被读取的文件名) |
dtype | 指定读取后的数据的数据类型,默认设置为float |
comments | 跳过文件中指定参数开关的行(即不读取) |
delimiter | 指定读取文件中数据的分割符 |
converters | 对读取的数据进行预处理 |
skiprows | 选择跳过的行数 |
usecols | 指定需要读取的列 |
unpack | 选择是否将数据进行向量输出 |
encoding | 对读取的文件进行预编码 |
- 读取 .txt 文件
import numpy as np
## 读取 ”F:\\python_test\\“ 路径下文件numpy_test_1.txt
np.loadtxt("F:\\python_test\\numpy_test_1.txt")
运行结果
## skiprows:指跳过前1行, 如果设置skiprows=2, 就会跳过前两行,数据类型设置为整型。
np.loadtxt("F:\\python_test\\numpy_test_1.txt",skiprows=2,dtype=int)
运行结果
## comment, 如果行的开头为#就会跳过该行
np.loadtxt("F:\\python_test\\numpy_test_4.txt",skiprows=2,comments="#",delimiter=',')
np.loadtxt("F:\\python_test\\numpy_test_4.txt",comments="#",delimiter=',')
运行结果
## usecols:指定读取的列,若读取0,2两列
np.loadtxt('F:\\python_test\\numpy_test_3.txt',dtype=int, skiprows=1,delimiter=',',usecols=(0, 2))
运行结果
## unpack是指会把第一列当成一个列输出 ,而不是合并在一起。
(a,b)=np.loadtxt("F:\\python_test\\numpy_test_2.txt",skiprows=1,dtype=int,delimiter=',',usecols=(0,2),comments="#",unpack=True)
print(a,b,sep="\n")
运行结果
- 读取 .csv 文件
## 读取csv文件
np.loadtxt("F:\\python_test\\numpy_test_2.csv",dtype='float32', delimiter=',')
运行结果
- load()
load(file, mmap_model=None, allow_pickle=True, fix_import=True, encoding=‘ASCII’)
方法 | 描述 |
---|---|
file | 类文件对象或字符串格式。类文件对象需要支持seek()和read()方法。 |
mmap_mode | 内存映射模型。值域None。‘r+‘,’r’,‘w+’,‘c’。 |
allow_pickle | 布尔型。决定是否加载存储在npy文件pickled对象数组,默认为True。 |
fix_imports | 布尔型。如果为True,pickle尝试将旧的python2名称映射到python3中并使用新的名称。仅在python2生成的pickled文件加载到python3时才有用,默认为True。 |
encoding | string. Determines what encoding to use when reading python2 strings. |
- Read .npy files
import numpy as np
write_data=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
np.save("F:\\python_test\\load_data.npy",write_data) # 保存为npy数据文件,将数据存储为npy保存时可以省略扩展名,默认为.npy。
read_data=np.load('F:\\python_test\\load_data.npy') # 读取npy文件
print(read_data)
operation result
- Read .npz files
import numpy as np
write_data_1=np.arange(12).reshape(3,4)
np.savez("F:\\python_test\\load_data_1.npz",write_data) #多数组存储,默认文件名.npz
read_data_1=np.load("F:\\python_test\\load_data_1.npz") #读取.npz文件
for i in read_data_1.items():
print(i)
operation result
- fromfile()
fromfile(file, dtype=float, count=-1, sep=‘’)
method | describe |
---|---|
file | file or string. |
dtype | type of data. Note that the data type is consistent with the type of file storage. |
count | Integer type. The number of read data, -1 means read all data. |
sep | String, if file is a text file, then this value is the delimiter between data. If the check is empty (""), it means that the file is a binary file, and if there are multiple spaces, it will be treated as one space. |
- read binary file
import numpy as np
file_name = "F:\\python_test\\numpy_test_1.txt"
data = np.loadtxt(file_name, dtype='float32', delimiter=' ')
tofile_name = 'binary' # 定义导出二进制文件名
data.tofile(tofile_name) # 导出二进制文件
fromfile_data = np.fromfile(tofile_name, dtype='float32') # 读取二进制文件
print(fromfile_data)
operation result
Note : Be sure to ensure that the data type of the read-in file is consistent with that of the stored file, otherwise data errors will be reported. For example, if the above code does not specify the float32 format, take a look at the output. The data saved by the tofile() method loses the data shape information, so the original data matrix cannot be reproduced when imported.
import numpy as np
file_name = "F:\\python_test\\numpy_test_1.txt"
data = np.loadtxt(file_name, delimiter=' ')
tofile_name = 'binary' # 定义导出二进制文件名
data.tofile(tofile_name) # 导出二进制文件
fromfile_data = np.fromfile(tofile_name, dtype='float32') # 读取二进制文件
print(fromfile_data)
operation result