Find the name of a file except its directory [duplicate] - python

This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 1 year ago.
I used the following code to read all files in a folder:
files_path = [os.path.abspath(x) for x in os.listdir()]
fnames_transfer = [x for x in files_path if x.endswith(".mkv")]
Now I need to extract the name of the file except its directory. For example fnames_transfer is E:\pythoncode\feature\1.mkv. I need to extract 1.mkv from this string. What should I do for this?

I used this os.path.basename(fnames_transfer[i] )and it works for me.

Related

Using files in directory that are matching with a list [duplicate]

This question already has answers here:
Get a filtered list of files in a directory
(14 answers)
Closed 2 years ago.
I have a directory with a lot of audio files and a list that contains the names of some of these files. I want to process only the files in the directory that are matching with my name list.
My attempt (that is not working) is this:
path_to_audio_files = 'D:/Data_small/output_conv/'
sample_list = ['s1.wav', 's2.wav', 's3.wav']
import fnmatch
for file in os.listdir(path_to_audio_files):
if fnmatch.fnmatch(file, sample_list):
fs, signal = wavfile.read(file)
Is this even the right way to do it or how can it be done?
Thanks!
Why use fnmatch (I have never heard of it) instead of python native capabilities? (in operator)
path_to_audio_files = 'D:/Data_small/output_conv/'
sample_list = ['s1.wav', 's2.wav', 's3.wav']
for file in os.listdir(path_to_audio_files):
if file in sample_list:
fs, signal = wavfile.read(file)

How to remove extension from multiple files in python [duplicate]

This question already has an answer here:
Batch File Rename with Python
(1 answer)
Closed 2 years ago.
I have a folder which have more than 100 files. The folder contains.txt files. i want to remove ".txt" extension from all files. also tried os.path.splitext even os.remove it doesn't work.
You can use os.rename(). The file name is just a string. You can remove the 4 last characters with:
src = 'path_to_txt.txt'
dst = src[:-4]
os.rename(src, dst)
You can use stem from the pathlib module.
import pathlib
file_name = pathlib.Path(‘textfile.txt‘)
file_name_wo_ext = file_name.stem

split filename on name and extenstion in python [duplicate]

This question already has answers here:
Extracting extension from filename in Python
(33 answers)
Getting file extension using pattern matching in python
(6 answers)
Closed 5 years ago.
I have this pattern:
dir1/dir2/.log.gz
dir1/dir2/a.log.gz
dir1/dir2/a.py
dir1/dir2/*.gzip.tar
I want to get filename or path and extension. e.g:
(name,extension)=(dir1/dir2/,.log.gz)
(name,extension)=(dir1/dir2/a,.log.gz)
(name,extension)=(dir1/dir2/a,.py)
(name,extension)=(dir1/dir2/,.gzip.tar)
I try:
re.findall(r'(.*).*\.?(.*)',path)
but it doesn't work perfect
If you just want the file's name and extension:
import os
# path = C:/Users/Me/some_file.tar.gz
temp = os.path.splitext(path)
var = (os.path.basename(temp[0]), temp[1])
print (var)
# (some_file.tar, .gz)
Its worth noting that files with "dual" extensions will need to be recursed if you want. For example, the .tar.gz is a gzip file that happens to be an archive file as well. But the current state of it is .gz.
There is more on this topic here on SO.
General strategy: find the first '.' everything before it is the path, everything after it is the extension.
def get_path_and_extension(filename):
index = filename.find('.')
return filename[:index], filename[index + 1:]

Delete all files in a folder that doesn't have certain name [duplicate]

This question already has answers here:
Python - Delete all files EXCEPT for
(2 answers)
Closed 5 years ago.
So I have about 1200 folders with different content in each. In all of them there is one file that has a specific name, let's call it data.txt.
Now, due to lack of hard drive space I need to remove/delete all data in each folder that is not that particular file, i.e. data.txt.
Is this possible to do in python ? If so, how ? :)
Try This ( with OS module only ) :
import os
your_target_folder = "."
your_target_file_name = "data.txt"
for dirpath, _, filenames in os.walk(your_target_folder):
for items in filenames:
file_full_path = os.path.abspath(os.path.join(dirpath, items))
try:
if items == your_target_file_name:
os.remove(file_full_path)
except:
print("Error On " + str(file_full_path))
print("Done")

Python code, extracting extensions [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In python, how can I check if a filename ends in '.html' or '_files'?
import os
path = '/Users/Marjan/Documents/Nothing/Costco'
print path
names = os.listdir(path)
print len(names)
for name in names:
print name
Here is the code I've been using, it lists all the names in this category in terminal. There are a few filenames in this file (Costco) that don't have .html and _files. I need to pick them out, the only issue is that it has over 2,500 filenames. Need help on a code that will search through this path and pick out all the filenames that don't end with .html or _files. Thanks guys
for name in names:
if filename.endswith('.html') or filename.endswith('_files'):
continue
#do stuff
Usually os.path.splitext() would be more appropriate if you needed the extension of a file, but in this case endswith() is perfectly fine.
A little shorter than ThiefMaster's suggestion:
for name in [x for x in names if not x.endswith(('.html', '_files'))]:
# do stuff

Categories

Resources