1

I'm iterating through files in a directory and would like to save the filename and some stuff I extract from the files in the same pandas dataframe. How can I save the names the txt files in a list (which I would then insert into pandas dataframe as a separate column) while going through all the files in a directory?

Here's part of my code:

columns_df = ['file', 'stuff']
df_stuff = pd.DataFrame(columns = columns_df)

filenamelist = []
stufflist = []

os.chdir(r'path\to\directory')
for file in glob.glob('*.txt'):
    # Extract some stuff from file and append to stufflist (DONE)
    # Save filename in the filenamelist (THE PROBLEM)

df_stuff['stuff'] = stufflist
df_stuff['file'] = filenamelist
est
  • 25
  • 4

1 Answers1

0

Do you need this functionality?

for file in glob.glob('*.txt'):
    filenamelist.append(file)
Alexandra Dudkina
  • 4,302
  • 3
  • 15
  • 27