Rename all files that match with a regex [duplicate] - python

This question already has answers here:
Python renaming file with regex
(6 answers)
Closed 19 days ago.
I have the files in following format:
abc-h-25-Data.db
abc-h-25-Filter.db
abc-h-25-Index.db
abc-h-25-Metadata.db
abc-h-25-Statistics.db
abc-h-25-Summary.db
Need to rename by replacing the h by j as follows:
abc-j-25-Data.db
abc-j-25-Filter.db
abc-j-25-Index.db
abc-j-25-Metadata.db
abc-j-25-Statistics.db
abc-j-25-Summary.db
Any bash/python script that can automate this for me? Thanks!

i write basic script to rename file names according to your requirement and if you want any help for the same comment here
import os
path = "folder-path"
for root, dirs, files in os.walk(path):
for filename in files:
if "abc-h-25-" in filename:
os.rename(root+filename, root+filename.replace("abc-h-25-", "abc-j-25-" ))
print(filename)

You can use the following command to automate this task:
for file in abc-h-*; do mv "$file" "${file/h/j}"; done
Here's a bash script that performs the same task as the above command, but with descriptive variable names:
#!/bin/bash
old_prefix="abc-h-"
new_prefix="abc-j-"
for filename in "${old_prefix}"*; do
new_filename="${filename/$old_prefix/$new_prefix}"
mv "$filename" "$new_filename"
done
Here's a Python script that performs the same task as the previous bash scripts:
import os
old_prefix = "abc-h-"
new_prefix = "abc-j-"
for filename in os.listdir():
if filename.startswith(old_prefix):
new_filename = filename.replace(old_prefix, new_prefix)
os.rename(filename, new_filename)

You can use os.rename() function and glob function to rename the files with specific patterns in specific paths. My approach to your problem is as follows.
import os
import glob
# Absolute Path of folder with files.
files_path = r"C:\Users\User1\Documents\GitHub\files"
# Regex Pattern to filter specific files in folder.
regex_pattern = "abc-h*.db"
all_files = glob.glob(f'{files_path}\{regex_pattern}')
for i in all_files:
os.rename(i, i.replace("h", "j"))
print("Sucessful!")

Related

How do I output a recursive list of files to a text file without using glob (python3.4)

I am trying to recursively go through all the directories in the "boards" directory and find files that end in '.vhd' and then output them to a text file. I am using python 3.4 so I don't have access to recursive glob.
path = '../../boards'
rel_paths = open('rel_paths.txt', 'a+')
files = [os.path.join(dirpath, f)
for dirpath, dirnames, files in os.walk(path)
for f in files
if f.endswith('.vhd')]
I want 'rel_paths.txt' to look like this in the inside:
../../boards/foo/bar/file_name1.vhd
../../boards/foo/bars/file_name2.vhd
if you are flexible you can use Unix command " find " instead of writing python code as follows
find ../../boards -name "*.vhd" >> rel_paths.txt
it can be modified to suit what you need

Rename Single .txt File In Multiple Subdirectories

I have ~60 subdirectories in a single directory. Each of these contain thousands of files, but they all contain a file named test_all_results.txt.
What I would like to do is to rename each test_all_results.txt file so that it now has the name:
foldername_all_results.txt
What is the best way to do this?
Easily accomplished using Python os interface.
Assuming you are currently in the main directory:
import os
#get a list of all sub directories
subdir = os.listdir()
for dir in subdir:
if os.path.isdir(dir): #check if directory
os.chdir(dir) #move to sub directory
os.rename('test_all_results.txt', 'foldername_all_results.txt')
os.chdir('..') #return to main directory
Using python in Linux, make this:
import os
os.system("mv old_name.txt new_name.txt")
You can automatize with a loop, renaming all filenames.
You can do:
(change your code accordingly)
import os
# current directory is the target
direct = "."
for path, dirs, files in os.walk(direct):
for f in files:
if os.path.splitext(f)[0] == "test_all_results.txt":
os.rename(os.path.join(path, f), os.path.join(path, "foldername_all_results.txt"))
There's an answer that tells you to use the os.system() method, if you do decide to call Linux commands from Python, I'd advise that you use the subprocess module instead.
Here's how you'd run the mv command with two arguments using subprocess.call:
import subprocess
subprocess.call(["mv", "filename.txt", "new-name.txt"])
INFO: here's an old (but relevant) article that explains why it's dangerous to use these methods.
Good luck.

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

error with splitting file path string by / in python [duplicate]

This question already has answers here:
How to split a dos path into its components in Python
(23 answers)
Closed 6 years ago.
This is what I'm doing. I'm taking a text from a folder, modifying that text, and writing it out to another folder with a modified file name. I'm trying to establish the file name as a variable. Unfortunately this happens:
import os
import glob
path = r'C://Users/Alexander/Desktop/test/*.txt'
for file in glob.glob(path):
name = file.split(r'/')[5]
name2 = name.split(".")[0]
print(name2)
Output: test\indillama_Luisa_testfile
The file name is 'indillama_Luisa_testfile.txt' it is saved in a folder on my desktop called 'test'.
Python is including the 'test\' in the file name. If I try to split name at [6] it says that index is out of range. I'm using regex and I'm assuming that it's reading '/*' as a single unit and not as a slash in the file directory.
How do I get the file name?
You can split by the OS path separator:
import os
import glob
path = r'C://Users/Alexander/Desktop/test/*.txt'
for file in glob.glob(path):
name = file.split(os.path.sep)[-1]
name2 = name.split(".")[0]
print(name2)
import os
import glob
path = r'C://Users/Alexander/Desktop/test/*.txt'
for file in glob.glob(path):
name = os.path.basename(file)
(path, ext) = os.path.splitext(file)
print(ext)
os.path.basename() will extract the filename part of the path. os.path.splitext() hands back a tuple containing the path and the split-off extension. Since that's what your example seemed to be printing, that's what I did in my suggested answer.
For portability, it's usually safer to use the built-in path manipulation routines rather than trying to do it yourself.
You can use os.listdir(path) to list all the files in a directory.
Then iterate over the list to get the filename of each file.
for file in os.listdir(path):
name2 = file .split(".")[0]
print(name2)

Filename scanning for certain names Python [duplicate]

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

Categories

Resources