Python Forum
Checking a filename before reading it with pd.read_csv - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Checking a filename before reading it with pd.read_csv (/thread-22101.html)



Checking a filename before reading it with pd.read_csv - karlito - Oct-29-2019

Hi Guys,

I'm trying to read a csv file according to its type (X or Y, so if the file name starts with 125 I read the raw_file1 file otherwise raw_file2) but when I run the code I get no ouput.

Thks for help
Karlito

import string
import pandas as pd
import numpy as np

raw_file1 = '2340595954_header.csv' #csv typ X
raw_file2 = '4325670000_things.csv' #csv typ Y

# Get the first 3 digit/character of the raw_file1
first_3_char_raw_file1  = ''.join([s[0:3] for s in raw_file1.split(' ')]) #234

# Check if the first 3 digits/characters of the raw_file1 are 234(csv-type X) or 432(csv-type Y) 
#if yes then read raw_file1
if first_3_char_raw_file1 == 125:
    data = pd.read_csv(raw_file1)

    '''do something'''

    #data.head()
#else read raw_file2
else:
    data = pd.read_csv(raw_file2)

    '''do something'''

    #data.head()



RE: Checking a filename before reading it with pd.read_csv - scidam - Oct-29-2019

There is str.startswith method. So, you can just do:
if raw_file1.startswith('125'):
    pass # or do something
else:
    pass  # or do something



RE: Checking a filename before reading it with pd.read_csv - karlito - Oct-30-2019

(Oct-29-2019, 10:11 PM)scidam Wrote: There is str.startswith method. So, you can just do:
if raw_file1.startswith('125'):
    pass # or do something
else:
    pass  # or do something

Thks