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

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

Related

delete images containing specific word in its name using python [duplicate]

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)

How do I use a method to change the file extension in Python? [duplicate]

This question already has answers here:
Change the file extension for files in a folder?
(7 answers)
Closed 2 years ago.
I have a folder full of .txt files and would like to change them to .dat using a method. From what I have researched I have constructed the portion of code below. However, when I run it nothing is changed and they stay as .txt.
def ChangeFileExt(path, curr_ext, new_ext)
with os.scandir(path) as itr:
for entry in itr:
if entry.name.endswith(curr_ext):
name = entry.name.split('.')
name = name + '.' + new_ext
src = os.path.join(path,entry.name)
dst = os.path.join(path,name)
os.rename(src, dst)
The following is what i will do, that may be robust in many situations.
import glob
from pathlib import Path
from shutil import copyfile
# glob all the absolute file directories
f_glob = "/[the absolute directory]/*.txt"
ls_f_dirs = glob.glob(f_glob)
# loops through the file directories list for renaming
# (i will create a new folder storing the copied/renamed file
# but will not be renaming the original files directly on the existing folder.
for f_dir in ls_f_dirs:
# to get the file stem excluding the extension
f_stem = Path(f_dir).stem
# copying the file to new file name in a new absolute directory
copyfile(f_dir, '/[the new storing absolute directory]/{}.bat'.format(f_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:]

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

python zipfile module: How to change the structure of zip archive created? [duplicate]

This question already has answers here:
How to eliminate absolute path in zip archive if absolute paths for files are provided?
(6 answers)
Closed 6 years ago.
I wrote the following code in order to zip bin_file_path:
zf = zipfile.ZipFile(file_to_search, mode='w')
zf.write(bin_file_path)
zf.close()
If bin_file_path is for example: \dir1\dir2\bin_file, then when I unzip the zip file created, I get a directory named "dir1", inside another directory named "dir2" and only inside "dir2" I'll get the bin_file.
I want that the zip file created contains bin_file directly and not inside of sub_directories. Do you have an idea how to do it?
You can use
zf = zipfile.ZipFile(file_to_search, mode='w')
zf.write(bin_file_path, custom_name)
zf.close()
where custom_name can be anything including os.path.basename(bin_file_path).

Categories

Resources