Home > database >  How to store and pass a filename to as a variable in python
How to store and pass a filename to as a variable in python

Time:12-01

I have the beginnings of some python that will take columns out of a specific csv file and then rename the csv columns something else. The issue that I have is the CSV file will always be in the same directory this script is ran in, but the name won't always be the same (and there will only ever be one csv in the directory at a time)

Is there a way to automatically grab the csv name and pass it as a variable? Here is what I have so far:

`


import pandas as pd

#df = pd.read_csv("csv_import.csv",skiprows=1) #==> use to skip first row (header if required)
df = pd.read_csv("test.csv") #===> Include the headers
correct_df = df.copy()
correct_df.rename(columns={'Text1': 'Address1', 'Text2': 'Address2'}, inplace=True)


#Exporting to CSV file
correct_df.to_csv(r'.csv', index=False,header=True)

`

What I'm looking for is to not have to specify "test.csv" and instead have it grab the name of the csv inthe directory.

CodePudding user response:

You can use glob.glob to return a list of the files matching a pattern (e.g *.csv) and then slice.

Try this :

from glob import glob
import pandas as pd

csv_file = glob("*.csv")[0]

df= pd.read_csv(csv_file)

CodePudding user response:

You can get list of all files in directory(in this case csv files) using os.listdir():

import os
csvfiles = [p for p in os.listdir() if p.endswith(".csv")]
  • Related