Python Forum
Checking a filename before reading it with pd.read_csv
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Checking a filename before reading it with pd.read_csv
#1
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()
Reply
#2
There is str.startswith method. So, you can just do:
if raw_file1.startswith('125'):
    pass # or do something
else:
    pass  # or do something
Reply
#3
(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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pandas read_csv markf7319 0 1,274 Mar-03-2022, 04:59 AM
Last Post: markf7319
  pandas read_csv can't handle missing data mrdominikku 0 2,509 Jul-09-2020, 12:26 PM
Last Post: mrdominikku
  read_csv error and rows/columns missing karlito 9 5,348 Nov-11-2019, 06:48 AM
Last Post: karlito
  utf-8 error with pandas read_csv logues 0 3,876 Oct-23-2018, 05:25 PM
Last Post: logues
  pandas read_csv, numbers in footer mechanic310 1 2,822 May-22-2018, 10:38 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020