Python - 在 Pandas 中读取文件夹中的所有 CSV 文件?
pythonserver side programmingprogramming更新于 2025/11/17 0:12:17
要读取文件夹中的所有 excel 文件,请使用 Glob 模块和 read_csv() 方法。假设以下是目录 − 中的 excel 文件
首先,让我们设置路径并获取 csv 文件。我们的 CSV 文件位于文件夹 MyProject − 中
path = "C:\Users\amit_\Desktop\MyProject\"
从上述路径读取扩展名为 .csv 的文件 −
filenames = glob.glob(path + "\*.csv")
现在让我们编写一个 for 循环来迭代所有 csv 文件,读取并打印它们 −
for file in filenames:
# 读取 csv 文件
print("\nReading file = ",file)
print(pd.read_csv(file))
示例
以下是完整代码 −
import pandas as pd
import glob
# 获取来自文件夹 MyProject 的 csv 文件
path = "C:\Users\amit_\Desktop\MyProject\"
# 读取所有扩展名为 .csv 的文件
filenames = glob.glob(path + "\*.csv")
print('File names:', filenames)
# for 循环迭代所有 csv 文件
for file in filenames:
# 读取 csv 文件
print("\nReading file = ",file)
print(pd.read_csv(file))
输出
这将产生以下输出
File names:['C:\Users\amit_\Desktop\MyProject\Sales1.xlsx','C:\Users\amit_\Desktop\MyProject\Sales2.xlsx'] Reading file = C:\Users\amit_\Desktop\MyProject\Sales1.xlsx Car Place UnitsSold 0 Audi Bangalore 80 1 Porsche Mumbai 110 2 RollsRoyce Pune 100 Reading file = C:\Users\amit_\Desktop\MyProject\Sales2.xlsx Car Place UnitsSold 0 BMW Delhi 95 1 Mercedes Hyderabad 80 2 Lamborgini Chandigarh 80
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

