I am trying to open the two most recent .csv files from a folder stored on my hard drive. Upon reading in each df, I want to create a column containing the name of the file that was read in, but I keep getting KeyError: 'file_name'.
Any help would be greatly appreciated.
Thanks!
files = glob.glob(r"path\*.csv")
sorted_files = sorted(files, key=os.path.getmtime, reverse = True) #sorting files from newest to oldest
buyandsell_df = []
for index, file in enumerate(sorted_files):
if index == 2: #only open two most recent files from sorted_files list
break
else:
print("READING IN " + file)
df = pd.read_csv(file, usecols=['language','title','contract_number','publishing_status','award_date','publication_date','amendment_date','contract_value'], low_memory = False)
df['file_name'] = file
df = df.loc[df['language'] == 'English'] # filter out french duplicates
buyandsell_df.append(df)
dfobject after thedf = pd.read_csv(...)line? - FCo'file_name'is not indf- Benjamin W.df['file_name']exists?df=pd.read_csv...is producing a data frame not a file. - Adrian Klaver