Python:从目录中读取文件并连接它

时间:2016-09-19 08:47:31

标签: python pandas directory

我有一个带有et文件的文件夹.csv,我尝试阅读该文件,然后连接并获取一个文件。 我试试

import os

path = 'et/'
for filename in os.listdir(path):
    et = open(filename)
    print et

但是我收到了错误

Traceback (most recent call last):
File "C:/Users/����� �����������/Desktop/projects/PMI/join et.py", line 5, in <module>
et = open(filename)
IOError: [Errno 2] No such file or directory: '0et.csv'

我无法理解,为什么我会得到这个错误,因为当我 print filename 我得到了

0et.csv
1et.csv
2et.csv
3et.csv
4et.csv
5et.csv
6et.csv
7et.csv
8et.csv

3 个答案:

答案 0 :(得分:0)

您可能希望使用et = open(path+filename),而不只是et = open(filename)

编辑:根据@thiruvenkadam的建议,最佳做法是使用et = open(os.path.join(path,filename))

答案 1 :(得分:0)

使用glob.glob将是一个更好的选择,同时使用os.path.join来获取完整路径:

from glob import glob
from os.path import join, abspath
from os import listdir, getcwd

import pandas as pd

data_frame = pd.DataFrame()
dir_path = "et"
full_path = join(abspath(getcwd()), dir_path, "*.csv")
for file_name in glob(full_path):
    csv_reader = pd.read_csv(file_name, names=columns)
    # Guessing that all csv files will have the header
    #If header is absent, use names=None
    data_frame = data_frame.append(csv_reader, ignore_index=True)
    # There is also a concat funtion to use. I am comfortable with append
    # For concat, it will be data_frame = pd.concat(data_frame, csv_reader, ignore_index=True)
  1. abspath将确保从根目录(在Windows的情况下,从主文件系统驱动器)中获取完整目录
  2. 在连接中添加* .csv将确保您将检查目录中的csv文件
  3. glob(full_path)将返回给定目录的绝对路径的csv文件列表
  4. 始终确保您将显式关闭文件描述符或使用with语句自动执行,因为这是一种干净的做法。任何C开发人员都可以保证最好关闭文件描述符。由于我们需要将值放在数据框中,因此我取出了with语句并从pandas中添加了read_csv。
  5. pandas.read_csv在阅读csv时会让生活变得更好,以防我们将csv文件内容写入数据帧。使用read_csv和pandas append(或concat),我们可以轻松编写csv文件,而无需编写其他csv文件的头文件内容。由于个人意见,我已经补充了。添加了如何在评论中使用concat。

答案 2 :(得分:-1)

也许是编码问题

您可以尝试在代码顶部添加以下代码

# -*- coding: utf-8 -*-