how can i rename files with different names at once in python - python

path = '/Users/my/path/tofile'
files = os.listdir(path)
names= ["GAT4", "LO", "sds"]
for filename in files:
if files.startswith("sample" + str[i]):
original_file= os.path.join(path, filename)
new_file= os.path.join(path, names.join([str(i), '.html']))
os.rename(original_file, new_file)
i have many files and i wanna rename all of them using a python code that changes the name depending on a given name from a list:
for example i have a list of x = [sample1, sample236, GAT988] and my files are named like: exp1.html exp2.html exp3.html
how can i make the files names become GAT988.html instead of exp3.html?enter code here
thank you.

Related

Python Merging files after a name fragment

I have two folders when I have dynamic quantity files.
For example:
In folder "A" I've files:
FileName_1.txt
FileName_2.txt
FileName_3.txt
In folder "B" I've files:
NewFile_1.txt
NewFile_2.txt
NewFile_3.txt
The number of files in both folders will always be the same. Is there any simple way how to merge files by number in filename? As result I want to:
Data from file NewFile_1.txt add to FileName_1.txt
Data from file NewFile_2.txt add to FileName_2.txt, etc.
It doesn't have to be a solution to the problem. Thank you for the tips.
Just something like this. Grab all the file names from the B directory, find the suffix (after the _), and open the A file based on that:
import os
newnames = [k for k in os.listdir( "B") if k[-4:] == '.txt']
for name in newnames:
i = name.find('_')
suffix = name[i:]
olddata = open('B/' + name).read()
open('A/FileName'+suffix, 'a').write(olddata)

How to get the full file path including the directory?

I have a quiet complex problem. I have multiple filenames in a list, the root directory of those files is the same: mother_directory. However every file has a different subdirectory. Now I have a script which is processing some files and I need to know the exact full path including the subdirectories of every file. I know that I could use os.walk but that will make my function too nested as inside this function I'm planning to use another function which uses those full paths.
This is the file structure:
mother_directory:
|_child1:
20211011.xml
20211001.xml
|_child2:
20211002.xml
This is my current code:
mother_path = r'c:\data\user1\Desktop\mother_directory'
blue_dates = ['20211011', '20211012', '20211013', '20211001', '20211002']
red_dates = ['20211011', '20211009', '20211008', '20211001', '20211002']
file_names = ['20211011.xml', '20211001.xml', '20211002.xml']
def process_files(x):
if x in red_dates:
match_file = [s for s in file_names if x in s]
file_path = os.path.join(mother_path, match_file [0])
print(file_path)
for x in blue_dates:
process_files(x)
My current output:
c:\data\user1\Desktop\mother_directory\20211011.xml
c:\data\user1\Desktop\mother_directory\20211001.xml
c:\data\user1\Desktop\mother_directory\20211002.xml
When I run my function I want my desired output to be like this:
c:\data\user1\Desktop\mother_directory\child1\20211011.xml
c:\data\user1\Desktop\mother_directory\child1\20211001.xml
c:\data\user1\Desktop\mother_directory\child2\20211002.xml
I added a condition, I believe it will work now.
def process_files(x):
if x in red_dates:
match_file = [s for s in file_names if x in s]
for root, dirs, files in os.walk(mother_path):
for file in files:
if match_file[0] in file:
print(os.path.join(root,match_file[0]))

Rename specific files in a folder

I am trying to do a program that renames the files that are not named in order for example :
input: in a folder we have these files : ['spam001.txt', 'spam002.txt', 'spam003.txt', 'spam005.txt', 'spam007.txt']
output: i want to end up with the same files named like this : ['spam001.txt', 'spam002.txt', 'spam003.txt', 'spam004.txt', 'spam005.txt']
Here is what i have done until now :
import os,shutil
count = 1
path = '.\\filling in the gaps' #this is the folder where i have the .txt files
files = os.listdir(path)
for i in files:
if(i[6] != str(count)):
os.rename(os.path.join(path,i),'spam00%s.txt' %(count))
count = count+1
My problem is that when I run the program, for the output mentioned above , I get ['spam001.txt', 'spam002.txt', 'spam003.txt'] in the 'filling in the gaps' folder and I get
['spam004.txt', 'spam005.txt'] in the folder that contains 'filling in the gaps' folder.
Basically, my program renames the files, but the files end up in another folder. Any idea why this is happening?
This is where the files go:
Here is a working version of your code, providing your desired results:
import os
count = 1
path = '.\\filling in the gaps' # this is the folder where i have the .txt files
files = os.listdir(path)
for i in files:
if (i[6] != str(count)):
os.rename(os.path.join(path, i),
os.path.join(path, 'spam00%s.txt' % (count))
)
count = count + 1

How to erase certain names in files with Python

I am trying to erase certain names of subfolders that were download with weird names containing useless information, (in this case, these are movie files so things like 720p, BluRay, etc.)
My code so far is this:
os.chdir(r"E:\Users\Lucas\HD externo\Filmes_séries_documentários\Diretores")
lista = ["1080p","720p", "BDrip", "BRRip", "Xvid", "XViD","XviD", "ETRG", "Woody Allen", "DVDRip", "avi", "x264", "AC3-JYK", "BluRay", "DC", ".....anoXmous", "EXTENDED", "pt", "BR"]
for i in range(len(os.listdir())):
for b in os.listdir():
os.chdir(r"E:\Users\Lucas\HD externo\Filmes_séries_documentários\Diretores\\" + os.listdir()[i])
for c in range(len(os.listdir())):
for item in lista:
if item in os.listdir()[i]:
a = os.listdir()[i].replace(item, "")
os.rename(os.listdir()[i], a)
It's a good idea to use os.walk when looking through a directory structure.
If you want to remove the file, I'd use os.remove(filename)
import os
dir = r"C:\Windows\Path\"
lista = ['all','of','the','things']
for root, dirs, files in os.walk(dir):
for file in files:
for part in lista:
if part in file:
os.remove(os.path.join(root, file))

Rename multiple files inside multiple folders

So I have a lot of folders with a certain name. In each folder I have +200 items. The items inside the folders has names like:
CT.34562346.246.dcm
RD.34562346.dcm
RN.34562346.LAO.dcm
And some along that style.
I now wish to rename all files inside all folders so that the number (34562346) is replaced with the name of the folder. So for example in the folder named "1" the files inside should become:
CT.1.246.dcm
RD.1.dcm
RN.1.LAO.dcm
So only the large number is replaced. And yes, all files are similar like this. It would be the number after the first . that should be renamed.
So far I have:
import os
base_dir = "foo/bar/" #In this dir I have all my folders
dir_list = []
for dirname in os.walk(base_dir):
dir_list.append(dirname[0])
This one just lists the entire paths of all folders.
dir_list_split = []
for name in dir_list[1:]: #The 1 is because it lists the base_dir as well
x = name.split('/')[2]
dir_list_split.append(x)
This one extracts the name of each folder.
And then the next thing would be to enter the folders and rename them. And I'm kind of stuck here ?
The pathlib module, which was new in Python 3.4, is often overlooked. I find that it often makes code simpler than it would otherwise be with os.walk.
In this case, .glob('**/*.*') looks recursively through all of the folders and subfolders that I created in a sample folder called example. The *.* part means that it considers all files.
I put path.parts in the loop to show you that pathlib arranges to parse pathnames for you.
I check that the string constant '34562346' is in its correct position in each filename first. If it is then I simply replace it with the items from .parts that is the next level of folder 'up' the folders tree.
Then I can replace the rightmost element of .parts with the newly altered filename to create the new pathname and then do the rename. In each case I display the new pathname, if it was appropriate to create one.
>>> from pathlib import Path
>>> from os import rename
>>> for path in Path('example').glob('**/*.*'):
... path.parts
... if path.parts[-1][3:11]=='34562346':
... new_name = path.parts[-1].replace('34562346', path.parts[-2])
... new_path = '/'.join(list(path.parts[:-1])+[new_name])
... new_path
... ## rename(str(path), new_path)
... else:
... 'no change'
...
('example', 'folder_1', 'id.34562346.6.a.txt')
'example/folder_1/id.folder_1.6.a.txt'
('example', 'folder_1', 'id.34562346.wax.txt')
'example/folder_1/id.folder_1.wax.txt'
('example', 'folder_2', 'subfolder_1', 'ty.34562346.90.py')
'example/folder_2/subfolder_1/ty.subfolder_1.90.py'
('example', 'folder_2', 'subfolder_1', 'tz.34562346.98.py')
'example/folder_2/subfolder_1/tz.subfolder_1.98.py'
('example', 'folder_2', 'subfolder_2', 'doc.34.34562346.implication.rtf')
'no change'
This will rename files in subdirectories too:
import os
rootdir = "foo" + os.sep + "bar"
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filepath = subdir + os.sep + file
foldername = subdir.split(os.sep)[-1]
number = ""
foundnumber = False
for c in filepath:
if c.isdigit():
foundnumber = True
number = number + c
elif foundnumber:
break
if foundnumber:
newfilepath = filepath.replace(number,foldername)
os.rename(filepath, newfilepath)
Split each file name on the . and replace the second item with the file name, then join on .'s again for the new file name. Here's some sample code that demonstrates the concept.
folder_name = ['1', '2']
file_names = ['CT.2345.234.dcm', 'BG.234234.222.dcm', "RA.3342.221.dcm"]
for folder in folder_name:
new_names = []
for x in file_names:
file_name = x.split('.')
file_name[1] = folder
back_together = '.'.join(file_name)
new_names.append(back_together)
print(new_names)
Output
['CT.1.234.dcm', 'BG.1.222.dcm', 'RA.1.221.dcm']
['CT.2.234.dcm', 'BG.2.222.dcm', 'RA.2.221.dcm']

Categories

Resources