python常见打开文件的方式示例详解
作者:Daydream.V
一、python自带
1.1 open()
open(file, mode,encoding)
这里的file指的是你要读取的文件,mode指的是读取方式,encoding指的是打开文件的编码方式。
注意使用此函数时需要在文件读取结束后,需要手动close
f = open('test.txt', 'r', encoding='utf-8')
content = f.read()
f.close() 1.2 with open()(此函数不需要手动close)
with open() 的核心其实是 open() 函数
open(file, mode, encoding)
file指的是你要读取的文件,mode指的是读取方式,encoding指的是打开文件的编码方式。
with open("test.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)二、第三方库
2.1 Pandas(表格文件:CSV/Excel/TXT)
df = pd.read_csv(
filepath_or_buffer='文件路径/URL',
sep=',',
header=0,
names=['列1', '列2', '列3'],
encoding='utf-8'
)其中 filepath_or_buffer='文件路径/URL', 为文件路径或网络链接, sep=',', 为分隔符,默认逗号,制表符用'\t',header=0, 为表头行,无表头填None, names=['列1', '列2', '列3'],为自定义列名(header=None时用), encoding='utf-8' 为编码方式中文乱码换gbk/gb2312
import pandas as pd
df = pd.read_csv(
# 基础参数
filepath_or_buffer='student_scores.csv',
encoding='utf-8',
sep=',',
)2.2 NumPy(数值文件:.npy/.txt)
np.loadtxt(fname, dtype=float, comments='#', delimiter=None, skiprows=0, usecols=None, unpack=False)
其中fname为文件路径或文件对象,dtype指定数组数据类型(默认 float),delimiter分隔符(默认空格),skiprows跳过前 N 行(如跳过表头 / 注释),usecols只读取指定列(索引),comments注释符(默认#,跳过注释行),unpack是否拆分列为独立数组(默认 False)。
arr_loadtxt = np.loadtxt(
fname='numpy_simple.csv',
dtype={'names': ('学号', '数学', '语文'), 'formats': ('U6', 'int', 'int')}, # 自定义结构化类型
delimiter=',',
)2.3 Pillow(图片文件:JPG/PNG/BMP)
PIL.Image.open(fp, mode='r', formats=None)
fp字符串 / 文件对象必选!指定图片文件路径、文件对象,或支持的网络流
mode字符串打开模式,仅支持 'r'(只读),Pillow 不支持写入模式(写入用 save())
formats列表 / None限定尝试解析的图片格式,避免 Pillow 自动检测格式出错,提升读取效率。
img = Image.open(
fp='test_image.png',
mode='r',
formats=['PNG']
)到此这篇关于python常见打开文件的方式的文章就介绍到这了,更多相关python打开文件方式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
