Ank
Ank

Reputation: 6270

read only csv files python

I can read all csv files like this in python:

import glob
for files in glob.glob("*.csv"):
    print files

However I only want to read the files that have just .csv as suffix. For example I would only wanna read

file.csv and not

file.x.csv

or

file.x.y.csv

What is a good way to do this?

Upvotes: 0

Views: 3256

Answers (4)

user1749431
user1749431

Reputation: 569

You can use a regex that matches .csv at the end of each string, filename is a variable for a string with the .csv at the end.

import re

if re.search('\.csv', filename):
     do something

Upvotes: 0

mojo
mojo

Reputation: 4142

Use filter() and a regex.

import glob
import re

flt = re.compile(r'^[^.]+\.csv$',re.I)
for f in filter(flt.match,glob.glob('*.csv')):
    print(f)

The regex here assumes that there is only a single period in the file name. Your needs might require a different regex.

Upvotes: -1

jramirez
jramirez

Reputation: 8685

you could use count

import glob
for files in glob.glob("*.csv"):
    # print all files that contain only .csv
    if files.count('.') == 1:
       print files

Upvotes: 5

YXD
YXD

Reputation: 32521

Add a guard like

if '.' not in os.path.basename(files)[:-4]

Upvotes: 0

Related Questions