在 Python 的世界里,读取文件和导入数据是极为基础且重要的操作,无论是进行数据分析、处理文本,还是开发各类应用,都离不开这两项技能。今天,咱们就来深入探讨一下 Python 在这方面的各种门道。
在 Python 中,打开文件的基础操作是使用open函数。比如,我们要读取一个名为example.txt的文本文件,代码可以这样写:
file = open('example.txt', 'r')content = file.read()file.close()print(content)这里,open函数的第一个参数是文件名,第二个参数'r'表示以只读模式打开文件。读取完内容后,使用close方法关闭文件,这是良好的编程习惯,能释放系统资源。不过,这种写法存在一个风险,如果在读取过程中发生异常,文件可能无法正常关闭。这时候,with语句就派上用场了,它能自动处理文件的打开和关闭,让代码更安全、简洁:
cee.qianxinancw.com with open('example.txt', 'r') as file: content = file.read() print(content)在with语句块结束时,文件会自动关闭,即使发生异常也不例外。
with open('small_file.txt', 'r') as file: content = file.read() print(content)with open('large_file.txt', 'r') as file: cef.xiaoda.net line = file.readline() while line: print(line.strip()) # 使用strip方法去除行末的换行符 line = file.readline()with open('file.txt', 'r') as file: lines = file.readlines() for line in lines: print(line.strip())with open('big_file.txt', 'r') as file: for line in file: print(line.strip())在使用open函数时,文件模式是个关键参数,它决定了我们对文件的操作权限和方式。常见的文件模式有:
with open('image.jpg', 'rb') as file: binary_data = file.read()在实际工作中,我们经常会遇到不同编码格式的文件,如 UTF - 8、GBK 等。如果不指定编码,Python 会使用系统默认编码,这可能导致读取乱码。因此,明确指定文件编码非常重要。比如读取一个 UTF - 8 编码的文件:
with open('utf8_file.txt', 'r', encoding='utf-8') as file: content = file.read() print(content)如果要读取 GBK 编码的文件,只需将编码参数改为'gbk'即可:
with open('gbk_file.txt', 'r', encoding='gbk') as file: content = file.read() print(content)对于大文件,直接一次性读取显然不可取,除了前面提到的逐行读取,还可以采用分块读取的方式。比如,每次读取 1KB 的数据块:
with open('large_file.txt', 'r') as file: while True: chunk = file.read(1024) # 读取1KB的数据块 if not chunk: break print(chunk)这种方式可以有效控制内存占用,让程序在处理大文件时也能稳定运行。
在文件读取过程中,可能会遇到各种错误,如文件不存在、权限不足等。为了使程序更加健壮,我们需要进行错误处理。使用try - except ceh.vcbjjdt.cn语句可以捕获并处理这些异常:
try: with open('nonexistent.txt', 'r') as file: content = file.read()except FileNotFoundError: print("文件不存在")except IOError as e: print(f"读取文件时出错: {e}")这样,当文件不存在时,程序会打印 “文件不存在”;当发生其他 I/O 错误时,会打印具体的错误信息。
在数据分析、机器学习等领域,从不同数据源导入数据是第一步。Python 提供了丰富的库来支持各种数据格式的导入。
numbers = []with open('cei.zqsedu.com', 'r') as file: for line in file: number = int(line.strip()) numbers.append(number)print(numbers)import numpy as npfilename ='mnist.txt'data = np.loadtxt(filename, skiprows=2, usecols=(0, 2))print(data)import numpy as npfilename = 'cej.honganpr.com'data = np.genfromtxt(filename, delimiter=',', names=True, dtype=None)print(data)import pandas as pdfilename = 'cek.jiubae.com'data = pd.read_csv(filename, nrows=5, header=None, sep='\t', na_values="")print(data)Pandas 提供了便捷的方式来读取 Excel 文件。在读取之前,需要确保安装了openpyxl库(用于处理 xlsx 格式文件)。例如,有一个名为data.xlsx的 Excel 文件,要读取其中名为Sheet1的工作表数据:
import pandas as pddata = pd.read_excel('cel.czygcj.com', sheet_name='Sheet1')print(data)如果 Excel 文件包含多个工作表,要读取所有工作表,可以使用ExcelFile类:
import pandas as pdfile = 'cem.keprinting.com'xls = pd.ExcelFile(file)sheets = {}for sheet_name in xls.sheet_names: sheets[sheet_name] = pd.read_excel(xls, sheet_name=sheet_name)print(sheets)import jsonwith open('data.json', 'r') as file: data = json.load(file) print(data)如果 JSON 文件是按行存储多个 JSON 对象,需要逐行解析,可以这样做:
import jsonwith open('lines.json', 'r') as file: for line in file: data = json.loads(line.strip()) print(data)import sqlite3conn = sqlite3.connect('example.db')cursor = conn.cursor()cursor.execute('SELECT * FROM users')rows = cursor.fetchall()for row in rows: print(row)conn.close()如果使用 Pandas 从 SQLite 数据库读取数据,可以结合read_sql_query函数,使数据处理更加便捷:
import pandas as pdimport sqlite3conn = sqlite3.connect('example.db')data = pd.read_sql_query('SELECT * FROM users', conn)print(data)conn.close()from sas7bdat import SAS7BDATwith SAS7BDAT('demo.sas7bdat') as file: df_sas = file.to_data_frame()print(df_sas)import pandas as pddata = pd.read_stata('demo.dta')print(data)import picklewith open('pickled_demo.pkl', 'rb') as file: pickled_data = pickle.load(file)print(pickled_data)import h5pyfilename = 'data.h5'data = h5py.File(filename, 'r')print(data.keys())import scipy.iofilename = 'cep.dnzpack.com'mat = scipy.io.loadmat(filename)print(mat)Python 读取文件和导入数据的方法丰富多样,针对不同的文件类型和数据格式,我们可以选择最合适的工具和方法。熟练掌握这些技能,将为我们在 Python 编程的道路上,尤其是在数据分析、机器学习等领域,打下坚实的基础。无论是处理日常的文本数据,还是应对复杂的大规模数据集,都能游刃有余。希望通过今天的分享,大家能对 Python 在这方面的应用有更深入的理解和掌握。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。