How to add prefix in glob.glob for path patching - python-2.7

there:
I am trying to use a prefix as a input in glob.glob() function to pull out the png files in my folder. For example: I have dog_1.png, dog_2.png, bird_1.png, bird_2.png in this folder. my input is dog but for some reason, python pulled out nothing. Can you please do me a favor check where I did wrong? Thank you in advance!
dir_name = 'mypath'
if __name__=='__main__':
prefix = raw_input('Input the prefix of images:')
files = glob.glob( dir_name + prefix + '*.png')
print files
What I got is []

Your path to glob is malformed. You'll need to specify your path like this: dir_name/<file>.png (note the forward slash /). You can do this nicely using os.path.join.
import os
glob.glob(os.path.join(dir_name, prefix + '*.png'))

Related

In VSCode, how can I replace text with file information?

In VSCode, I'd like to replace a particular string, say x, across a directory with the name of the file in which that string appears. Can I do this from the search menu? If not, is there an extension I can use?
You could use a simple python script like this to loop through a directory use regex to get the files you want to change and then change them to what you want.
import os
import re
from pathlib import Path
p = Path('C:/Users/user/Pictures')
files = []
for x in p.iterdir():
a = re.search('.*(jpe?g|png)',str(x))
if a is not None:
files.append(a.group())
old_file_name = a.group()
new_file_name = newname
os.rename(old_file_name, new_file_name)

Python shutil file move in os walk for loop

The code below searches within a directory for any PDFs and for each one it finds it moves into the corresponding folder which has '_folder' appended.
Could it be expressed in simpler terms? It's practically unreadable. Also if it can't find the folder, it destroys the PDF!
import os
import shutil
for root, dirs, files in os.walk(folder_path_variable):
for file1 in files:
if file1.endswith('.pdf') and not file1.startswith('.'):
filenamepath = os.path.join(root, file1)
name_of_file = file1.split('-')[0]
folderDest = filenamepath.split('/')[:9]
folderDest = '/'.join(folderDest)
folderDest = folderDest + '/' + name_of_file + '_folder'
shutil.move(filenamepath2, folderDest)
Really I want to traverse the same directory after constructing the variable name_of_file and if that variable is in a folder name, it performs the move. However I came across issues trying to nest another for loop...
I would try something like this:
for root, dirs, files in os.walk(folder_path_variable):
for filename in files:
if filename.endswith('.pdf') and not filename.startswith('.'):
filepath = os.path.join(root, filename)
filename_prefix = filename.split('-')[0]
dest_dir = os.path.join(root, filename_prefix + '_folder')
if not os.path.isdir(dest_dir):
os.mkdir(dest_dir)
os.rename(filepath, os.path.join(dest_dir, filename))
The answer by John Zwinck is correct, except it contains a bug where if the destination folder already exists, a folder within that folder is created and the pdf is moved to that location. I have fixed this by adding a 'break' statement within the inner for loop (for filename in files).
The code below now executes correctly. Looks for folder named as the pdf's first few characters (taking the prefix split at '-') with '_folder' at the tail, if it exists the pdf is moved into it. If it doesn't, one is created with the prefix name and '_folder' and pdf is moved into it.
for root, dirs, files in os.walk(folder_path_variable):
for filename in files:
if filename.endswith('.pdf') and not filename.startswith('.'):
filepath = os.path.join(root, filename)
filename_prefix = filename.split('-')[0]
dest_dir = os.path.join(root, filename_prefix + '_folder')
if not os.path.isdir(dest_dir):
os.mkdir(dest_dir)
os.rename(filepath, os.path.join(dest_dir, filename))
break

How to rename JPG files with running order using Python

I quite new in Python programming and i try to rename 100 files with ".jpg" extention, located in specific folder using pyhthon.
I need that the files will be renamed by running order start from number 1. This is the code i start writing:
import os,glob,fnmatch
os.chdir(r"G:\desktop\Project\test")
for files in glob.glob("*.jpg"):
print files
When i run it, i get:
>>>
er3.jpg
IMG-20160209-ssdeWA0000.jpg
IMG-20160209-WA0000.jpg
sd4.jpg
tyu2.jpg
uj7.jpg
we3.jpg
yh7.jpg
>>>
so the code, till now is OK.
For example my folder is:
and i need that all the files name will be:
1,2,3,4 - with running order names. Is it possible with python 2.7?
If you simply want to rename all files as 1.jpg, 2.jpg etc. you can do this:
import os
import glob
os.chdir(r"G:\desktop\Project\test")
for index, oldfile in enumerate(glob.glob("*.jpg"), start=1):
newfile = '{}.jpg'.format(index)
os.rename (oldfile,newfile)
enumerate() is used to get get the index of each file from the list returned by glob(), so that it can be used to create the new filename. Note that it allows you to specify the start index, so I've started from 1, rather than Python Standard, zero
If you want this list of files to be sortable properly, you'll want the filename to be padded with zero's as well (001.jpg, etc.). In which case simply replace newfile = '{}.jpg'.format(index)' with newfile = '{:03}.jpg'.format(index).
See the the docs for more on str.format()
To rename all the JPG files from a particular folder First, get the list of all the files contain in the folder.
os.listdir will give you list all the files in images path.
use enumerate to get the index numbers to get the new name for
images.
import os
images_path = r"D:\shots_images"
image_list = os.listdir(images_path)
for i, image in enumerate(image_list):
ext = os.path.splitext(image)[1]
if ext == '.jpg':
src = images_path + '/' + image
dst = images_path + '/' + str(i) + '.jpg'
os.rename(src, dst)
import os
from os import path
os.chdir("//Users//User1//Desktop//newd//pics")
for file in os.listdir():
name,ext=path.splitext(file)
if ext == '.jpeg':
dst= '{}.jpg'.format(name)
os.rename(file,dst)

listing directories having "-" character in directories name

I want to list the directories in current directory having "-" character in directories name. I used os.listdir(path). Its giving me error :
"WindowsError: [Error 123] The filename, directory name, or volume
label syntax is incorrect:"
Any help will be greatly appreciated
Use os.listdir to get directory contents and then filter using os.path.isdir to check if each item is a dir:
dirs_with_hyphen = []
for thing in os.listdir(os.getcwd()):
if os.path.isdir(thing) and '-' in thing:
dirs_with_hyphen.append(thing)
print dirs_with_hyphen # or return, etc.
And that can be shortened using list comprehension:
dirs_with_hyphen = [thing for thing in os.listdir(os.getcwd()) if os.path.isdir(thing) and '-' in thing]
I'm using os.getcwd but you could pass in any string that represents a folder.
If you're getting an error about the filename being incorrect, you're probably not escaping correctly or it's not pointing to the right folder (absolute vs relative path issue).
I did some testing and I managed to get your error. I don't know if this is what you did to get the error though since no example has been provided.
What I did though is give an invalid drive path. Not one that could be valid and doesn't exist, one that is always wrong eg.'C::\' or 'CC:\' just anything that's not 'C:\'. As for your question.
Path should generally look like this, prefixing with r to ignore backslash as escape character or double backslash.
import os
path = r"C:\Users\Steven\Documents\"
path = "C:\\Users\\Steven\\Documents\"
for file in os.listdir(path):
if os.path.isdir(path+file) and '-' in file:
print path + file
#List Comp
[path+file for file in os.listdir(path) if os.path.isdir(path+file) and '-' in file]

Registered Trademark: Why does strip remove ® but replace can't find it? How do I remove symbols from folder and file names?

If the registered trademark symbol does not appear at the end of a file or folder name, strip cannot be used. Why doesn't replace work?
I have some old files and folders named with a registered trademark symbol that I want to remove.
The files don't have an extension.
folder: "\data\originals\Word Finder®"
file 1: "\data\originals\Word Finder® DA"
file 2: "\data\originals\Word Finder® Thesaurus"
For the folder, os.rename(p,p.strip('®')) works. However, replace os.rename(p,p.replace('®','')) does not work on either the folder or the files.
Replace works on strings fed to it, ie:
print 'Registered® Trademark®'.replace('®',''). Is there a reason the paths don't follow this same logic?
note:
I'm using os.walk() to get the folder and file names
I have been unable to recreate your issue, so I'm not sure why it isn't working for you. Here is a workaround though: instead of using the registered character in your source code with the string methods, try being more explicit with something like this:
import os
for root, folders, files in os.walk(os.getcwd()):
for fi in files:
oldpath = os.path.join(root, fi)
newpath = os.path.join(root, fi.decode("utf-8").replace(u'\u00AE', '').encode("utf-8"))
os.rename(oldpath, newpath)
Explicitly specifying the unicode codepoint you're looking for can help eliminate the number of places your code could be going wrong. The interpreter no longer has to worry about the encoding of your source code itself.
My original question 'Registered Trademark: Why does strip remove ® but replace can't find it?' is no longer applicable. The problem isn't strip or replace, but how os.rename() deals with unicode characters. So, I added to my question.
Going off of what Cameron said, os.rename() seems like it doesn't work with unicode characters. (please correct me if this is wrong - I don't know much about this). shutil.move() ultimately gives the same result that os.rename() should have.
Despite ScottLawson's suggestion to use u'\u00AE' instead of '®', I could not get it to work.
Basically, use shutil.move(old_name,new_name) instead.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import shutil
import os
# from this answer: https://stackoverflow.com/q/1033424/3889452
def remove(value):
deletechars = '®'
for c in deletechars:
value = value.replace(c,'')
return value
for root, folders, files in os.walk(r'C:\Users\myname\da\data\originals\Word_4_0'):
for f in files:
rename = remove(f)
shutil.move(os.path.join(root,f),os.path.join(root,rename))
for folder in folders:
rename = remove(folder)
shutil.move(os.path.join(root,folder),os.path.join(root,rename))
This also works for the immediate directory (based off of this) and catches more symbols, chars, etc. that aren't included in string.printable and ® doesn't have to appear in the python code.
import shutil
import os
import string
directory_path = r'C:\Users\myname\da\data\originals\Word_4_0'
for file_name in os.listdir(directory_path):
new_file_name = ''.join(c for c in file_name if c in string.printable)
shutil.move(os.path.join(directory_path,file_name),os.path.join(directory_path,new_file_name))