在Python中,你可以使用os
模块来遍历文件夹,使用pandas
库来读取CSV文件。以下是一个示例代码,展示了如何从多个文件夹中读取多个CSV文件:
os.walk()
函数可以遍历指定目录及其子目录中的所有文件和文件夹。pandas.read_csv()
函数可以方便地读取CSV文件内容。import os
import pandas as pd
def read_csv_from_folders(root_dir):
all_data = []
for root, dirs, files in os.walk(root_dir):
for file in files:
if file.endswith('.csv'):
file_path = os.path.join(root, file)
try:
df = pd.read_csv(file_path)
all_data.append(df)
except Exception as e:
print(f"Error reading {file_path}: {e}")
return pd.concat(all_data, ignore_index=True)
# 使用示例
root_directory = 'path/to/your/root/directory'
combined_data = read_csv_from_folders(root_directory)
print(combined_data.head())
pd.read_csv()
函数中指定正确的编码格式,如encoding='utf-8'
或encoding='gbk'
。通过上述方法和代码示例,你可以有效地从多个文件夹中读取多个CSV文件,并处理可能遇到的常见问题。
领取专属 10元无门槛券
手把手带您无忧上云