This question already has answers here:
How do I get the filename without the extension from a path in Python?
(31 answers)
Closed 3 years ago.
I am trying to get the filenames in a directory without getting the extension. With my current code -
import os
path = '/Users/vivek/Desktop/buffer/xmlTest/'
files = os.listdir(path)
print (files)
I end up with an output like so:
['img_8111.jpg', 'img_8120.jpg', 'img_8127.jpg', 'img_8128.jpg', 'img_8129.jpg', 'img_8130.jpg']
However I want the output to look more like so:
['img_8111', 'img_8120', 'img_8127', 'img_8128', 'img_8129', 'img_8130']
How can I make this happen?
You can use os's splitext.
import os
path = '/Users/vivek/Desktop/buffer/xmlTest/'
files = [os.path.splitext(filename)[0] for filename in os.listdir(path)]
print (files)
Just a heads up: basename won't work for this. basename doesn't remove the extension.
Here are two options
import os
print(os.path.splitext("path_to_file")[0])
Or
from os.path import basename
print(basename("/a/b/c.txt"))
Related
This question already has answers here:
How do i search directories and find files that match regex?
(4 answers)
Closed 8 months ago.
In the directory there are multiple images with names:
I want to delete all images with "340" in it using a python code.
Assuming that the images are in desktop/images/
I'm not sure why you need to use Python and can't just use your shell (in bash it would just be rm desktop/images/*340*)
But in Python I think the shortest way would be
import os, glob
for file in glob.glob("desktop/images/*340*"):
os.remove(file)
or even:
import os, glob
[os.remove(file) for file in glob.glob("desktop/images/*340*")]
You can use this example, you'll have to adjust the code for your correct directory:
import os
import re
for file in os.listdir("Desktop/Images"):
if re.search("340.*?\.jpg$", file):
os.remove("Desktop/Images/" + file)
print("Deleted " + file)
else:
print("No match for " + file)
This question already has answers here:
How do I get the filename without the extension from a path in Python?
(31 answers)
Closed 1 year ago.
I have the following:
selstim = '/Users/folder1/folder2/folder9/Pictures/Set_1/Pos/43et1.jpg'
I need to end up with:
43et1
I tried:
selstim.split('/')[-1]
Which produced:
43et1.jpg
I also tried:
selstim.split('/,.')[-1]
That doesn't get the desired result.
Is there a way to also get rid of the '.jpg' in the same line of code?
You may just find it easier to use pathlib (if you have Python 3.4+) and let it separate the path components for you:
>>> from pathlib import Path
>>> p = Path('/Users/folder1/folder2/folder9/Pictures/Set_1/Pos/43et1.jpg')
>>> p.stem
43et1
Implementation using only the standard os library.
from os import path
filePath = path.basename("/Users/folder1/folder2/folder9/Pictures/Set_1/Pos/43et1.jpg")
print(filePath) # 43et1.jpg
print(path.splitext(filePath)[0]) # 43et1, index at [1] is the file extension. (.jpg)
All in one line:
path.splitext(path.basename(FILE_PATH))[0]
This question already has answers here:
Why do backslashes appear twice?
(2 answers)
Closed 2 years ago.
I have one folder say ABC in which i have so many files with extension say 001.py, 001.xls, 001.pdf and many more. I want to write one program in which we get list with this filename say
["C:\Users\Desktop\ABC\001.py", "C:\Users\Desktop\ABC\001.xls", "C:\Users\Desktop\ABC\001.pdf"]
MyCode:
import os
from os import listdir
from os.path import isfile, join
dir_path = os.path.dirname(os.path.realpath(__file__))
print(dir_path) #current path
cwd = os.getcwd()
list3 = []
onlyfiles = [f for f in listdir(cwd) if isfile(join(cwd, f))]
for i in onlyfiles:
list3.append(dir_path+"\\"+i)
print(list3)
I am getting output as :
["C:\\Users\\Desktop\\ABC\\001.py", "C:\\Users\\Desktop\\ABC\\001.xls", "C:\\Users\\Desktop\\ABC\\001.pdf"]
I am looking for output as :
["C:\Users\Desktop\ABC\001.py", "C:\Users\Desktop\ABC\001.xls", "C:\Users\Desktop\ABC\001.pdf"]
If you can use Python 3, pathlib can help you assemble your paths in a clearer way! If you're forced to use Python 2, you could bring in the library it's based off!
The double-backslash occurs and needs to be dealt with because Windows bizarrely chose to use \ instead of / as the path separator while it is ubiquitous as an escape character in many, especially C-derived languages. You can use / and it'll still work fine. You'll find need to escape spaces with \ when not using pathlib too.
This question already has answers here:
Find all files in a directory with extension .txt in Python
(25 answers)
Closed 7 years ago.
I have lots of files in a directory, lets say around 100, most of their file names begin with "Mod", i need to add all filenames that begin with "Mod" to a list so i can reference them later in my code. Any help? Thanks!
Use the glob package.
import glob
filepaths = glob.glob('/path/to/file/Mod*')
More generally, you can use os.listdir. Unlike glob, it only returns the last part of the filename (without the full path).
import os
directory = '/path/to/directory'
filenames = os.listdir(directory )
full_filepaths = [os.path.join(directory, f) for f in filenames]
only_files = [f for f in full_filepaths if os.path.isfile(f)]
You can use glob library to find the files with the given pattern:
import glob,os
mylist=[]
os.chdir("/mydir")
for file in glob.glob("Mod*"):
mylist.append(file)
print mylist
or you can use os.walk
for root, dirs, files in os.walk('/mydir'):
for names in files:
if names.startswith("Mod"):
mylist.append(os.path.join(root, names))
This question already has answers here:
How do I list all files of a directory?
(21 answers)
Closed 9 years ago.
I have this code:
allFiles = os.listdir(myPath)
for module in allFiles:
if 'Module' in module: #if the word module is in the filename
dirToScreens = os.path.join(myPath, module)
allSreens = os.listdir(dirToScreens)
Now, all works well, I just need to change the line
allSreens = os.listdir(dirToScreens)
to get a list of just files, not folders.
Therefore, when I use
allScreens [ f for f in os.listdir(dirToScreens) if os.isfile(join(dirToScreens, f)) ]
it says
module object has no attribute isfile
NOTE: I am using Python 2.7
You can use os.path.isfile method:
import os
from os import path
files = [f for f in os.listdir(dirToScreens) if path.isfile(f)]
Or if you feel functional :D
files = filter(path.isfile, os.listdir(dirToScreens))
"If you need a list of filenames that all have a certain extension, prefix, or any common string in the middle, use glob instead of writing code to scan the directory contents yourself"
import os
import glob
[name for name in glob.glob(os.path.join(path,'*.*')) if os.path.isfile(os.path.join(path,name))]