how to rename files in a folder using pathlib in python? - python-3.x

I need help renaming .jpg files in my folder with the same prefix, 'cat_'. for example, 070.jpg should be renamed cat_070.jpg.
the files are located within the Cat folder:
from pathlib import Path
p = Path('C:\\Users\\me\\Jupiter_Notebooks\\Dataset\\Train\\Cat\\')
so I dont quite see how to do it? the below is wrong because it does not 'look into' the files in this directory.
p.rename(Path(p.parent, 'cat_' + p.suffix))
I have also unsuccessfully tried this:
import os
from os import rename
from os import listdir
# Get path
cwd = "C:\\Users\\me\\Jupiter_Notebooks\\Dataset\\Train\\Cat"
# Get all files in dir
onlyfiles = [f for f in listdir(cwd) if isfile(join(cwd, f))]
for file in onlyfiles:
# Get the current format
if file[-4:]==(".jpg"):
s = file[1]
# Change format and get new filename
s[1] = 'cat'
s = '_'.join(s)
# Rename file
os.rename(file, s)
print(f"Renamed {file} to {s}")
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\me\\Jupiter_Notebooks\\Dataset\\Train\\Cat\\'
how can I do it? sorry I'm really a beginner here.

How about:
from pathlib import Path
img_dir = Path('C:\\Users\\me\\Jupiter_Notebooks\\Dataset\\Train\\Cat\\') # path to folder with images
for img_path in img_dir.glob('*.jpg'): # iterate over all .jpg images in img_dir
new_name = f'cat_{img_path.stem}{img_path.suffix}' # or directly: f'cat_{img_path.name}'
img_path.rename(img_dir / new_name)
print(f'Renamed `{img_path.name}` to `{new_name}`')
pathlib also supports renaming files, so the os module is not even needed here.

use pathlib. Path. iterdir() to rename all files in a directory
1) for path in pathlib. Path("a_directory"). iterdir():
2) if path. is_file():
3) old_name = path. stem. original filename.
4) old_extension = path. suffix. original file extension.
5) directory = path. parent. ...
6) new_name = "text" + old_name + old_extension.
7) path. rename(pathlib.

Related

How to print relative path in file

So, I am trying to output folder & file structure to a txt file, using the below code. But I want to get relative paths outputed instead of absolute paths.
import os
absolute_path = os.path.dirname(__file__)
with open("output.txt", "w", newline='') as a:
for path, subdirs, files in os.walk(absolute_path):
a.write(path + os.linesep)
for filename in files:
a.write('\t%s\n' % filename)
For now this gives me something like this
C:\Users\User\OneDrive\bla\bla
C:\Users\User\OneDrive\bla\bla\folder1
file1.xxx
file2.xxx
file3.xxx
C:\Users\User\OneDrive\bla\bla\folder2
test1.txt
but I want to show only relative paths to where the script ran, not more
.\bla
.\bla\folder1
file1.xxx
file2.xxx
file3.xxx
.\bla\folder2
test1.txt
I have fiddled around a bit, but not getting to the solution, nor finding it here (or maybe I am not searching for the correct thing)
Any help would be appreciated
If you know the path to you current module, and you know the path of each file you find, and all your files will be in subdirectories of the current directory, you can calculate the relative path yourself.
Strings have the .replace(string_to_replace, replacement_value) method which will do this for you.
import os
absolute_path = os.path.dirname(__file__)
with open("output.txt", "w", newline='') as a:
for path, subdirs, files in os.walk(absolute_path):
a.write(path.replace(absolute_path, '.') + os.linesep)
for filename in files:
a.write('\t%s\n' % filename)
Beauty of python is, it os.path module ready for this kind of problems. You can use os.path.relpath() function
import os
absolute_path = os.path.dirname(__file__)
with open("output.txt", "w", newline='') as a:
for path, subdirs, files in os.walk(absolute_path):
a.write('.\\' + os.path.relpath(path + os.linesep, start=absolute_path))
for filename in files:
a.write('\t%s\n' % filename)
Here start parameter is used to current directory from where relative path should be resolved.

Read folders in folder one by one

I am trying to read folders in one folder, and analyse the daten in these folders. My idea is to write two loop: one to choose the folder, one to analyse daten in the chosen folder. But i don't know how can i write the new path with iterate variable. line3 of this snapshot is my problem.
Thank you for any input.
If you only want to get the folders inside another folder (subfolders) and aren't interested in other files that could be in the root folder you could use:
import os
path = '...'
for file_folder in os.listdir(path):
path1 = os.path.join(path, file_folder)
if os.path.isdir(path1):
print(path1)
# do something
or
import glob
path = '...'
for folder in glob.glob(f'{path}/*/'):
# do something
In line number two & three from the image, you have written:
for file_folder in os.listdir(path):
path1 = 'path' + '\' + str(file_folder)
file_folder is like a temporary variable holding folder name value for a particular iteration.
It should instead be:
for file_folder in os.listdir(path):
path1 = 'path' + '\\' + file_folder

Why python os is working only on default directory and how to change it?

import os
import shutil
FileCount = 0
filelist = []
ext = str(input())
for foldername, subfolders, filenames in os.walk('F:\\'):
for filename in filenames:
if filename.endswith(ext):
txtFileCount+=1;
filelist.append(filename)
print(os.path.abspath(filename))
print(txtFileCount)
print(filelist)
output:
The files are of 'G' directory while chosen directory is 'F'.
G:\Pillow\filecheckerProject\free_cam_8_7_0.msi
G:\Pillow\filecheckerProject\BlueJ-windows-421.msi
G:\Pillow\filecheckerProject\free_cam_8_7_0.msi
G:\Pillow\filecheckerProject\mysql-installer-web-community-8.0.17.0.msi
G:\Pillow\filecheckerProject\PowerToysSetup.msi
5
['free_cam_8_7_0.msi', 'BlueJ-windows-421.msi', 'free_cam_8_7_0.msi', 'mysql-installer-web-community-8.0.17.0.msi', 'PowerToysSetup.msi']
When you do os.path.abspath(filename), you're passing just a filename, like 'free_cam_8_7_0.msi'. The abspath function can't know what folder you're talking about with just that information.
But os.walk is giving you the folder; you're just not using it.
for foldername, subfolders, filenames in os.walk('F:\\'):
for filename in filenames:
if filename.endswith(ext):
txtFileCount+=1;
filelist.append(filename)
filepath = os.path.join(foldername, filename) # join the folder name and the filename
print(os.path.abspath(filepath))

How to rename the files of different format from the same folder but different subfolder using python

I have one scenario where i have to rename the files in the folder. Please find the scenario,
Example :
Elements(Main Folder)<br/>
2(subfolder-1) <br/>
sample_2_description.txt(filename1)<br/>
sample_2_video.avi(filename2)<br/>
3(subfolder2)
sample_3_tag.jpg(filename1)<br/>
sample_3_analysis.GIF(filename2)<br/>
sample_3_word.docx(filename3)<br/>
I want to modify the names of the files as,
Elements(Main Folder)<br/>
2(subfolder1)<br/>
description.txt(filename1)<br/>
video.avi(filename2)<br/>
3(subfolder2)
tag.jpg(filename1)<br/>
analysis.GIF(filename2)<br/>
word.docx(filename3)<br/>
Could anyone guide on how to write the code?
Recursive directory traversal to rename a file can be based on this answer. All we are required to do is to replace the file name instead of the extension in the accepted answer.
Here is one way - split the file name by _ and use the last index of the split list as the new name
import os
import sys
directory = os.path.dirname(os.path.realpath("/path/to/parent/folder")) #get the directory of your script
for subdir, dirs, files in os.walk(directory):
for filename in files:
subdirectoryPath = os.path.relpath(subdir, directory) #get the path to your subdirectory
filePath = os.path.join(subdirectoryPath, filename) #get the path to your file
newFilePath = filePath.split("_")[-1] #create the new name by splitting the old name by _ and grabbing last index
os.rename(filePath, newFilePath) #rename your file
Hope this helps.
check below code example for the first filename1, replace path with the actual path of the file:
import os
os.rename(r'path\\sample_2_description.txt',r'path\\description.txt')
print("File Renamed!")

Python3 clip.duration of all mp4 files in a folder

I am new to Python (using Python 3.6) and would like to extract the duration (in seconds) of all mp4 files I have in one folder. Code I have is:
path2 = path_directory
from moviepy.video.io.VideoFileClip import VideoFileClip
for root, dirs, files in os.walk(path2):
for filename in files:
clip = VideoFileClip(files)
print(clip.duration)
If I define clip = VideoFileClip("name_of_one_specific_file.mp4") it correctly prints the length (i.e. 590seconds) of that specific file, so I guess the mistake is in how I walk through all the files. I would need a list of the duration for each of the 245 mp4 files I have in path2.
Thank you very much in advance.
You just have a small error:
path2 = path_directory
from moviepy.video.io.VideoFileClip import VideoFileClip
for root, dirs, files in os.walk(path2):
for filename in files:
clip = VideoFileClip(filename) # <= !!!
print(clip.duration)
You want to open filename, not files. filename is the name of one specific file, files is the list of all files in a directory.
There's a newer library, available from Python 3.4, that's generally easier to use than walk. It's pathlib.
This is how you can use it in your situation.
from pathlib import Path
from moviepy.video.io.VideoFileClip import VideoFileClip
path2 = r' -------- '
for filename in Path(path2).glob('*.mp4'):
clip = VideoFileClip(filename.as_posix())
print(clip.duration)

Resources