如何通过python csv()函数读取目录中的多个csv文件? [英] how to read multiple csv files in a directory through python csv() function?
问题描述
在我的目录之一中,我有多个CSV文件.我想通过python代码读取所有CSV文件的内容并打印数据,但直到现在我还是不能这样做.
In one of my directory, I have multiple CSV files. I wanted to read the content of all the CSV file through a python code and print the data but till now I am not able to do so.
所有CSV文件都具有相同的列数和相同的列名.
All the CSV files have the same number of columns and the same column names as well.
我知道一种列出目录中所有CSV文件并通过"os"模块和"for"循环遍历它们的方法.
I know a way to list all the CSV files in the directory and iterate over them through "os" module and "for" loop.
for files in os.listdir("C:\\Users\\AmiteshSahay\\Desktop\\test_csv"):
现在使用"csv"模块读取文件名
Now use the "csv" module to read the files name
reader = csv.reader(files)
直到这里,我希望输出是CSV文件的名称.碰巧被排序了.例如,名称是1.csv,2.csv等.但输出如下
till here I expect the output to be the names of the CSV files. which happens to be sorted. for example, names are 1.csv, 2.csv so on. But the output is as below
<_csv.reader object at 0x0000019F97E0E730>
<_csv.reader object at 0x0000019F97E0E528>
<_csv.reader object at 0x0000019F97E0E730>
<_csv.reader object at 0x0000019F97E0E528>
<_csv.reader object at 0x0000019F97E0E730>
<_csv.reader object at 0x0000019F97E0E528>
如果我在csv.reader()之后添加next()函数,则会得到下面的输出
if I add next() function after the csv.reader(), I get below output
['1']
['2']
['3']
['4']
['5']
['6']
这恰好是我的CSV文件名的缩写.这是部分正确的,但不是完全正确的.
This happens to be the initials of my CSV files name. Which is partially correct but not fully.
除此之外,一旦我迭代了文件,如何在屏幕上查看CSV文件的内容?今天我有6个档案.后来,我可能有100个文件.因此,在我的方案中不可能使用文件处理方法.
Apart from this once I have the files iterated, how to see the contents of the CSV files on the screen? Today I have 6 files. Later on, I could have 100 files. So, it's not possible to use the file handling method in my scenario.
有什么建议吗?
推荐答案
我建议您使用pandas库读取CSV. 在此处检查此答案:将多个csv文件导入到熊猫并连接到一个DataFrame
I would recommend reading your CSVs using the pandas library. Check this answer here: Import multiple csv files into pandas and concatenate into one DataFrame
尽管您一般都要求使用python,但是pandas在数据I/O方面做得很好,在我看来会为您提供帮助.
Although you asked for python in general, pandas does a great job at data I/O and would help you here in my opinion.
这篇关于如何通过python csv()函数读取目录中的多个csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!