如何在 python 中读取许多不同名称的 .CSV 文件?

How to read many of .CSV files with different names in python?

假设我有 1000 个 .CSV 文件,其中包含我员工的姓名。所以文件名中没有任何顺序或数字。有没有办法用 Python 语言对计算机说,从头到尾读取一个特殊文件夹中的文件,而不管它们的名字是什么? (数据是给谁的对我来说并不重要,我只需要抓取这些数据来分析)。

您可以读取目录中的所有 csv 文件,如下所示:

我的 csv:

col1,col2,col3
a,b,c
d,e,f

代码:

import glob
import csv

PATH = "/Users/stack/"

for file in glob.glob(PATH+"*.csv"):
    with open(file) as csvfile:
        spamreader = csv.reader(csvfile, delimiter=',')
        for row in spamreader:
            print(" ".join(row))

输出:

col1 col2 col3
a b c
d e f

Process finished with exit code 0

是的,你可以。我会使用一个简单的基于正则表达式的测试器来检查文件,所以基本上你正在做的是你正在使用 for 循环遍历目录并使用 if 语句,我们测试文件以查看它是否包含'。 .csv'。在此之后,我们打开文件并将其简单地附加到我们的输出中,您可以选择分析或存储为文件。我已经注释掉了输出到文件的选项,但是如果你愿意的话也可以。

import re

# Redefine this to the path of your folder:
folderPath = "SET UNIX PATH HERE"

output = None
for file in os.listdir(folderPath):
    if re.search(r'.csv', file):
        with open(file, r) as readFile:
            output += readFile.read()

# Uncomment this part if you would like to store the output to a file
# Define the path to the file that will be created:
# outputFilePath = "SET UNIX PATH"
# with open(outputFilePath, w+) as outputFile:
#     outputFile.write(output)

希望这对您有所帮助:)

使用如下代码:(将当前路径 (.) 替换为您的路径:

import os, fnmatch
import csv
listOfFiles = os.listdir('.')  
pattern = "*.csv"  
for entry in listOfFiles:  
    if fnmatch.fnmatch(entry, pattern):
        with open(entry, newline='') as csvfile:
            spamreader = csv.reader(csvfile)
            for line in spamreader:
                print(line)
##########使用 Danadas 包
import os, fnmatch
import pandas as pd

listOfFiles = os.listdir('.')  
pattern = "*.csv"  
for entry in listOfFiles:  
    if fnmatch.fnmatch(entry, pattern):
        read_File_as_DF=pd.read_csv(entry)
        print(read_File_as_DF)