How to remove all characters before the final \ [duplicate] - python

This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 6 years ago.
I have a variable called dllName that grabs the name of a dll that has been executed. Sometimes this dll is returned in the format of "kernel32.dll" and sometimes as "C:\Windows\system32\kernel32.dll".
The path can vary, what I am trying to achieve is the stripping of the "C:\Windows\system32\".
EDIT: Extract file name from path, no matter what the os/path format
My question is not the same as this question, as os.path.basename and os.path.split do not work in this situation.
For os.path.split the head is empty and the tail contains the whole path?

You could use :
path = 'C:\\Windows\\system32\\kernel32.dll'
print path.split('\\')[-1]
#=> kernel32.dll
or
import os.path
print os.path.basename(path)
or
import re
def extract_basename(path):
"""Extracts basename of a given path. Should Work with any OS Path on any OS"""
basename = re.search(r'[^\\/]+(?=[\\/]?$)', path)
if basename:
return basename.group(0)
print extract_basename(path)
This last example should work for any OS, any Path.
Here are some tests.

Related

printing all the ".lnk" filenames in foldes and sub folders [duplicate]

This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 2 years ago.
so there are alot of files with .lnk extension in the start menu folder C:\ProgramData\Microsoft\Windows\Start Menu\Programs i want to print all those file names so i tried this code:
import os
import glob
startmenu = r'C:\ProgramData\Microsoft\Windows\Start Menu\Programs'
os.chdir(startmenu)
for file in glob.glob("**/*.lnk", recursive = True):
print(file)
it prints the link to the files, but i want to print only the file names with the extension of ".lnk"
Convert the absolute path to list then take the last element from the list. See the below code.
import os
import glob
startmenu = r'C:\ProgramData\Microsoft\Windows\Start Menu\Programs'
os.chdir(startmenu)
for file in glob.glob("**/*.lnk", recursive=True):
print(os.path.split(file)[-1])

I want to rename all the .txt files on a dir to .csv using Python 3 [duplicate]

This question already has answers here:
Rename multiple files in a directory in Python
(15 answers)
Closed 4 years ago.
Looking to change the file extension from .txt to .csv
import os, shutil
for filename in os.listdir(directory):
# if the last four characters are “.txt” (ignoring case)
# (converting to lowercase will include files ending in “.TXT”, etc)
if filename.lower().endswidth(“.txt”):
# generate a new filename using everything before the “.txt”, plus “.csv”
newfilename = filename[:-4] + “.csv”
shutil.move(filename, newfilename)
You can use os and rename.
But let me give you a small advice. When you do these kind of operations as (copy, delete, move or rename) I'd suggest you first print the thing you are trying to achieve. This would normally be the startpath and endpath.
Consider this example below where the action os.rename() is commented out in favor of print():
import os
for f in os.listdir(directory):
if f.endswith('.txt'):
print(f, f[:-4]+'.csv')
#os.rename(f, f[:-4]+'.csv')
By doing this we could be certain things look ok. And if your directory is somewhere else than . You would probably need to do this:
import os
for f in os.listdir(directory):
if f.endswith('.txt'):
fullpath = os.path.join(directory,f)
print(fullpath, fullpath[:-4]+'.csv')
#os.rename(fullpath, fullpath[:-4]+'.csv')
The os.path.join() will make sure the directory path is added too.

Python: Read only file name, instead of path [duplicate]

This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 5 years ago.
How to get ONLY filename instead of full path?
For example:
path = /folder/file.txt
and i need to get:
filename = file.txt
How to do that?
You should use the os module:
import os
filename = os.path.basename(path)
For other path manipulations look here (for python 2.7) or here (for python 3)

How can I remove a prefix from a filename in Python? [duplicate]

This question already has answers here:
Get relative path from comparing two absolute paths
(6 answers)
Closed 5 years ago.
I want to write a script that receives a path to a directory and a path to a file contained in that directory (possibly nested many directories deep) and returns a path to this file relative to the outer directory.
For example, if the outer directory is /home/hugomg/foo and the inner file is /home/hugomg/foo/bar/baz/unicorns.txt I would like the script to output bar/baz/unicorns.txt.
Right now I am doing it using realpath and string manipulation:
import os
dir_path = "/home/hugomg/foo"
file_path = "/home/hugomg/foo/bar/baz/unicorns.py"
dir_path = os.path.realpath(dir_path)
file_path = os.path.realpath(file_path)
if not file_path.startswith(dir_path):
print("file is not inside the directory")
exit(1)
output = file_path[len(dir_path):]
output = output.lstrip("/")
print(output)
But is there a more robust way to do this? I'm not confident that my current solution is the right way to do this. Is using startswith together with realpath a correct way to test that one file is inside another? And is there a way to avoid that awkward situation with the leading slash that I might need to remove?
You can use the commonprefix and relpath of the os.path module to find the longest common prefix of two paths. Its always preferred to use realpath.
import os
dir_path = os.path.realpath("/home/hugomg/foo")
file_path = os.path.realpath("/home/hugomg/foo/bar/baz/unicorns.py")
common_prefix = os.path.commonprefix([dir_path,file_path])
if common_prefix != dir_path:
print("file is not inside the directory")
exit(1)
print(os.path.relpath(file_path, dir_path))
Output:
bar/baz/unicorns.txt

How do I select part of a filename (leave out the extension) in Python? [duplicate]

This question already has answers here:
How do I get the filename without the extension from a path in Python?
(31 answers)
Closed 8 years ago.
For example if I have the variable "file.txt", I want to be able to save only "file" to a variable. What I'd like is to eliminate whatever is beyond the last dot (including the dot). So if i had "file.version2.txt", I'd be left with "file.version2".
Is there a way to do this?
you have to use os.path.splitext
In [3]: os.path.splitext('test.test.txt')
Out[3]: ('test.test', '.txt')
In [4]: os.path.splitext('test.test.txt')[0]
Out[4]: 'test.test'
full reference for similar manipulations can be found here http://docs.python.org/2/library/os.path.html
Using the module os.path you can retrieve the full name of the file and then remove the extension:
import os
file_name, file_ext = os.path.splitext(os.path.basename(path_to_your_file))
If this is not too long you can do something like this if the file is in same directory
old_f = 'file.version2.txt'
new_f = old_f.split('.')
sep = '.'
sep.join(new_f[:-1]) # or assign it to a variable current_f = sep.join(new_f[:-1])

Categories