Home > Back-end >  Isolating file names from paths in python
Isolating file names from paths in python

Time:07-21

I am trying to isolate file names from paths imported using "filedialog.askopenfilenames". I am doing that so I can use them later in plots.

Let us say for example that I imported three excel files that have the following names: "sample_excel_1","sample_excel_2.xlsx","sample_excel_3.xlsx"

The output in my case is the full paths of the files( i.e., ('//tudelft.net/staff-homes/K/mkhadijeh/Desktop/Python/sample_excel_1.xlsx', '//tudelft.net/staff-homes/K/mkhadijeh/Desktop/Python/sample_excel_2.xlsx', '//tudelft.net/staff-homes/K/mkhadijeh/Desktop/Python/sample_excel_3.xlsx') )

I would like the outputs to be instead ("sample_excel_1","sample_excel_2.xlsx","sample_excel_3.xlsx")

Any help!

The code is below:

import tkinter
from tkinter import *
from tkinter import filedialog
import numpy as np


filename = filedialog.askopenfilenames(initialdir="c:/", title="Selecte a file", filetypes=(("Excel files", "*.xlsx"),("All files","*.*")))

a = filename
print(a)

I want a to be a list so I can easily access it later (i.e., ["sample_excel_1","sample_excel_2.xlsx","sample_excel_3.xlsx"] )

CodePudding user response:

Since you have the file name as the full path, and you want the names for later (future) process you could do one of the following:

1- loop through the list you have now and use os.path.basename to get the files name:

import os
import tkinter
from tkinter import *
from tkinter import filedialog
import numpy as np


filename = filedialog.askopenfilenames(initialdir="c:/", title="Selecte a file", filetypes=(("Excel files", "*.xlsx"),("All files","*.*")))

a = filename
a = [os.path.basename(path) for path in a]
print(a)

2- or using split lib, by splitting on '\' and get the last element in the generated list

filename = filedialog.askopenfilenames(initialdir="c:/", title="Selecte a file", filetypes=(("Excel files", "*.xlsx"),("All files","*.*")))

a = filename
a = [path.split('\')[-1] for path in a]
print(a)

CodePudding user response:

Then using the pathlib library is recommended for cross platform compatibility instead of os:

import tkinter
from tkinter import *
from tkinter import filedialog
import numpy as np
from pathlib import PurePath

a = []

filename = filedialog.askopenfilenames(initialdir="c:/", title="Selecte a file", filetypes=(("Excel files", "*.xlsx"),("All files","*.*")))

for f in filename:
    a.append(PurePath(filename).name)
print(a)

EDIT: I didn't see the multiple output that filename could generate. Fixed it.

  • Related