np.load()用于打开npz(包含多个数组)、npy(单个数组)文件。
numpy.load(file, mmap_mode=None, allow_pickle=True, fix_imports=True, encoding=‘ASCII’)
file : file-like object, string, or pathlib.Path. The file to read. File-like objects must support the seek() and read() methods. Pickled files require that the file-like object support the readline() method as well.
mmap_mode : {None, ‘r+’, ‘r’, ‘w+’, ‘c’}, optional. If not None, then memory-map the file, using the given mode :
mmap_mode | 具体操作 |
---|---|
‘r’ | Open existing file for reading only. |
‘r+’ | Open existing file for reading and writing. |
‘w+’ | Create or overwrite existing file for reading and writing. |
‘c’ | Copy-on-write: assignments affect data in memory, but changes are not saved to disk. The file on disk is read-only. |
encoding : str, optional. What encoding to use when reading Python 2 strings. Only useful when loading Python 2 generated pickled files on Python 3, which includes npy/npz files containing object arrays. Values other than(除了) ‘latin1’, ‘ASCII’, and ‘bytes’ are not allowed, as they can corrupt numerical data. Default: ‘ASCII’
不重要的参数我就没写啦
with np.load(file_name) as f:
print(f.files)
得到结果
['arr_1', 'arr_0']
说明只有两个文件,所以我可以他们的名字,具体地打开他们
with np.load(file_name) as f:
array_0, array_1 = f['arr_1'], f['arr_0']
还有一种方法,就是用列表解析遍历所有
with np.load(file_name) as f:
array_0, array_1 = [f['arr_%d' % i] for i in range(len(f.files))]
得到结果:`
print(array_0)
print(array_1)
>>>
[ 0 3 4 ... 48997 48998 48999]
[20626 4971 29315 ... 41341 18543 4568]
with open('filename.txt') as f:
str = f.read() #文件的读操作
with open('data.txt', 'w') as f:
f.write('hello world') #文件的写操作
前面讲的默认都是读取文本文件,并且是UTF-8编码的文本文件。要读取二进制文件,比如图片、视频等等,用’rb’模式打开文件即可
r: 以只读方式打开文件。文件的指针将会放在文件的开头。这是**默认模式**。
rb: 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。
r+: 打开一个文件用于读写。文件指针将会放在文件的开头。
rb+:以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。
w: 打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
wb: 以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
w+: 打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
wb+:以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
a: 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
ab: 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+: 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
ab+:以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。
file.read([size]) 将文件数据作为字符串返回,可选参数size控制读取的字节数
file.readlines([size]) 返回文件中行内容的列表,size参数可选
file.write(str) 将字符串写入文件
file.writelines(strings) 将字符串序列写入文件
file.close() 关闭文件
file.closed 表示文件已经被关闭,否则为False
file.mode Access文件打开时使用的访问模式
file.encoding 文件所使用的编码
file.name 文件名
file.newlines 未读取到行分隔符时为None,只有一种行分隔符时为一个字符串,当文件有多种类型的行结束符时,则为一个包含所有当前所遇到的行结束的列表
file.softspace 为0表示在输出一数据后,要加上一个空格符,1表示不加。这个属性一般程序员用不着,由程序内部使用
参考:
https://blog.csdn.net/msspark/article/details/86745391