使用Python跨不同目录读取更多CSV文件时,可以使用以下步骤:
os
和csv
库,以便处理文件和CSV数据。import os
import csv
os.getcwd()
函数获取当前工作目录的路径。current_dir = os.getcwd()
data
文件夹下的多个子文件夹中,可以使用os.path.join()
函数将当前工作目录和数据文件夹路径连接起来。data_dir = os.path.join(current_dir, 'data')
os.walk()
函数遍历目录,查找所有的CSV文件,并将它们的路径存储在一个列表中。csv_files = []
for root, dirs, files in os.walk(data_dir):
for file in files:
if file.endswith('.csv'):
csv_files.append(os.path.join(root, file))
csv.reader
对象逐行读取每个CSV文件的数据。for file_path in csv_files:
with open(file_path, 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
# 处理每一行的数据
通过以上步骤,你可以使用Python跨不同目录读取更多的CSV文件。根据实际需求,你可以在循环中对每个CSV文件的数据进行相应的处理、分析或存储。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云