Path to a file without basename [duplicate] - python

This question already has answers here:
How do I get the parent directory in Python?
(21 answers)
Closed 1 year ago.
How can I get the path of a file without the file basename?
Something like /a/path/to/my/file.txt --> /a/path/to/my/
Tried with .split() without success.

Use os.path.dirname(filename).

You can import os
>>> filepath
'/a/path/to/my/file.txt'
>>> os.path.dirname(filepath)
'/a/path/to/my'
>>>

(dirname, filename) = os.path.split(path)

Check subs of os.path
os.path.dirname('/test/one')

Since Python 3.4 you can use Pathlib.
from pathlib import Path
path = Path("/a/path/to/my/file.txt")
print(path.parent)

Related

Splitting string in python using multiple operations in one line [duplicate]

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]

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

get filenames in a directory without extension - 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 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"))

How to get only files in directory? [duplicate]

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))]

os.unlink multiple file in python [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Deleting files by type in Python on Windows
How can I delete all files with the extension ".txt" in a directory? I normally just do
import os
filepath = 'C:\directory\thefile.txt'
os.unlink(filepath)
Is there a command like os.unlink('C:\directory\*.txt') that would delete all .txt files? How can I do that?
Thanks!
#!/usr/bin/env python
import glob
import os
for i in glob.glob(u'*.txt'):
os.unlink (i)
should do the job.
Edit: You can also do it in "one line" using map operation:
#!/usr/bin/env python
import glob
import os
map(os.unlink, glob.glob(u'*.txt'))
Use the glob module to get a list of files matching the pattern and call unlink on all of them in a loop.
Iterate through all files in C:\directory\, check if the extension is .txt, unlink if yes.

Categories

Resources