在Python中,导入不同格式的文件通常需要使用特定的库或模块,以下是一些常见文件格式的导入方法:
CSV文件导入
使用标准Python库
import csvwith open('file.csv', newline='') as csvfile:reader = csv.reader(csvfile)for row in reader:print(row)
使用NumPy
import numpy as npdata = np.loadtxt('file.csv', delimiter=',')
使用Pandas
import pandas as pddf = pd.read_csv('file.csv')
图片格式导入
使用PIL(Python Imaging Library)
from PIL import Imageimg = Image.open('file.jpg')
使用OpenCV

import cv2img = cv2.imread('file.jpg')
其他文件格式导入
文本文件
with open('file.txt', 'r') as file:content = file.read()
JSON文件
import jsonwith open('file.json') as file:data = json.load(file)
注意事项
确保文件路径正确,文件存在于指定的路径中。
根据文件格式选择合适的库或模块。
文件读取时注意编码问题,可能需要指定编码格式。
以上是Python中导入不同格式文件的基本方法。
