How can I remove a file extension from a list with file names?

I use the following to get a list with all the files inside a directory called tokens :

 import os accounts = next(os.walk("tokens/"))[2] 

Conclusion:

 >>> print accounts ['.DS_Store', 'AmieZiel.py', 'BrookeGianunzio.py', 'FayPinkert.py', 'JoieTrevett.py', 'KaroleColinger.py', 'KatheleenCaban.py', 'LashondaRodger.py', 'LelaSchoenrock.py', 'LizetteWashko.py', 'NickoleHarteau.py'] 

I want to remove the .py extension from each item in this list. I managed to do this individually using os.path.splitext :

 >>> strip = os.path.splitext(accounts[1]) >>> print strip ('AmieZiel', '.py') >>> print strip[0] AmieZiel 

I'm sure I overdid it, but I can't figure out how to remove the file extension from all the items in the list using a for loop.

What would be the right way to do this?

+5
source share
1 answer

In fact, you can do this on one line with a list comprehension :

 lst = [os.path.splitext(x)[0] for x in accounts] 

But if you need / need a for loop, the equivalent code would be:

 lst = [] for x in accounts: lst.append(os.path.splitext(x)[0]) 

Notice that I saved the os.path.splitext(x)[0] . This is the safest way in Python to remove an extension from a file name. There is no function in the os.path module dedicated to this task, and when using str.split some solution could be solved, or something would be error prone.

+8
source

Source: https://habr.com/ru/post/1210291/


All Articles