How to read many of .CSV files with different names in python?
本问题已经有最佳答案,请猛点这里访问。
假设我有1000个
您可以读取如下目录中的所有csv文件:
我的CSV:
1 2 3 | col1,col2,col3 a,b,c d,e,f |
代码:
1 2 3 4 5 6 7 8 9 10 | 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)) |
输出:
1 2 3 4 5 | col1 col2 col3 a b c d e f Process finished with exit code 0 |
使用如下代码:(将当前路径(.)替换为您的路径:
1 2 3 4 5 6 7 8 9 10 | 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包
1 2 3 4 5 6 7 8 9 | 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) |
是的,你可以。我将使用一个简单的基于regex的测试程序来检查文件,因此本质上您要做的就是使用for循环来遍历目录,并使用if语句来测试文件以查看它是否包含".csv"。在此之后,我们打开文件,并将其附加到输出中,您可以选择分析该文件或将其存储为文件。不过,如果您愿意的话,我已经对输出到文件的选项进行了注释。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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) |
希望这有帮助:)