Getting the names of all files in a folder with python

Β·

2 min read

Getting the names of all files in a folder with python

Hello everybody! πŸ‘‹

Recently I needed to analyze a bunch of microRNAs 🧬(small pieces of RNA that negatively regulates gene expression). I had plots of this molecules, a pdf file for each of them, and I needed to sort them in an easily readable table. Piece of cake, right? 🍰 Yes, really easy... but they were over 500, there's no way I enter 500 cells manually.

I started to think πŸ€” in a way of doing this automatically, so I thought: "somebody must already have done this before". I did a little research in my friend Mr. Google and I found out some answers, but none of them solved my problem, so I took a bunch of minutes to figure it out.

What did I do?

Well, I used the os module (documentation here)🐍. This module lets you manipulate files and filepaths, so it suited me really well. Here's my code:

import os
cwd = os.getcwd()

with open("files_names.txt", "w") as a:
    for path, subdirs, files in os.walk(cwd):
       for filename in files:
         f = os.path.join(path, filename)
         a.write(str(f) + os.linesep)

First, I created a variable named cwd containing the working directory (given by os.getcwcd). Next step was opening every file in the directory, and using the os.walk() method the get every single file's name. The method os.path.join(dirpath, name) allowed me to keep the full path for every file (warning: this will also output the names of every file in every sub folder. I needed it for another task, but it can be modified easily). Finally, you have to output every row, that's why I used os.linesep, which by default (I think) uses the newline separator \n.

Output

As output, I got a text file called "files_names.txt" πŸ“, that I opened with Excel πŸ“Š and with a little text to column, I kept only the names of every file I needed. Success πŸ’ͺ.

I hope someone find this as useful as me!

Until next time! πŸ‘‹.

Β