如何在python中读取许多具有不同名称的.CSV文件? [重复]

问题描述 投票:-1回答:3

这个问题在这里已有答案:

考虑我有1000个.CSV文件,其中包含我的员工姓名。因此文件名中没有任何顺序或数字。有没有办法用Python语言对计算机说,从头到尾读取文件的特殊文件夹,无论他们的名字是什么? (对我来说,数据对谁来说并不重要,我只需要抓住这些数据进行分析)。

python windows csv file-read
3个回答
1
投票

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

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)
##########Using Danadas package
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)

3
投票

您可以在以下目录中读取所有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

1
投票

是的你可以。我会使用一个简单的基于正则表达式的测试程序来检查文件,所以你正在做的是你正在使用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)

希望这可以帮助 :)

© www.soinside.com 2019 - 2024. All rights reserved.