代码之家  ›  专栏  ›  技术社区  ›  Hasani

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

  •  0
  • Hasani  · 技术社区  · 6 年前

    .CSV 有我员工名字的档案。所以文件名中没有任何顺序或数字。有没有办法用Python语言对计算机说,不管文件名是什么,都要从头到尾在一个特殊的文件夹中读取文件? (数据对谁来说并不重要,我只需要抓取这些数据进行分析)。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Pradeep Pandey    6 年前

    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)
    
        2
  •  3
  •   madik_atma    6 年前

    您可以读取以下目录中的所有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
    
        3
  •  1
  •   aaaakshat    6 年前

    是的,你可以。我将使用一个简单的基于regex的测试程序来检查这个文件,因此基本上您所做的是使用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)
    

    希望这有帮助:)