Search code examples
pythonpython-2.7csvglob

Open file with generator - Python


I want to open a file from a directory with a python generator - it's a csv-file and in the dir are about 8 csv-files. Yes I know, I also could use the csv-lib, but I wonder if I could do it without the lib.

Here's my code so far:

vz = glob.glob("home/user/*csv")

data = [ open(i, 'r') for i in vz if "some_file_name" in i ]

After that I get:

print data

==> [<open file '/home/user/some_file_name.csv', mode 'r' at 0x1eb78a0>]

for i in data.readlines():
    print i

==> 'list' object has no attribute 'readlines'

Any ideas?


Solution

  • It seems that data is a list with one element, which is the file object you are trying to read. This should work:

    for i in data[0].readlines():
        print i