使用Python编写的load_data()函数实现数据加载功能
发布时间:2024-01-18 20:01:40
下面是一个使用Python编写的load_data()函数的示例,该函数可用于加载数据,并返回一个包含加载数据的列表。
import csv
def load_data(file_path):
data = []
try:
with open(file_path, 'r') as file:
reader = csv.reader(file)
next(reader) # 跳过标题行
for row in reader:
data.append(row)
except FileNotFoundError:
print(f"File {file_path} not found.")
except Exception as e:
print(f"An error occurred while loading the data: {str(e)}")
return data
该函数通过使用Python内置的CSV模块来读取CSV文件中的数据。在读取数据之前,函数会跳过CSV文件的标题行(即 行),将读取到的每一行数据添加到一个列表中。
函数有一个参数file_path,它用于指定要加载的数据文件的路径。如果文件路径无效,函数将输出错误消息。否则,函数将返回一个包含加载数据的列表。
以下是一个使用load_data()函数的示例:
data_file = 'data.csv'
loaded_data = load_data(data_file)
print(f"Loaded {len(loaded_data)} rows of data.")
for row in loaded_data:
print(row)
假设有一个名为data.csv的文件,其内容如下:
Name,Age,Country John,25,USA Anna,30,Germany Tom,35,UK
通过运行上述代码,将会输出:
Loaded 3 rows of data. ['John', '25', 'USA'] ['Anna', '30', 'Germany'] ['Tom', '35', 'UK']
这样,我们就可以将数据加载到Python中,并对其进行进一步的处理和分析。
