I want to rename all the files in a folder with python - python

from glob import glob
from os import rename
import time
arrr = []
def getnames():
with open("name.txt", "r+") as nameFile:
for name in nameFile:
nameFile.readline()
newlinestrip = name.strip("\n")
arrr.append(newlinestrip)
renames()
def renames():
for fname in glob('*.png'):
print(fname)
for name in arrr:
time.sleep(1)
rename(fname, name)
print("bruh")
getnames()
It renames the 1st file and the it crashes with the error
Traceback (most recent call last):
File ".\rename.py", line 24, in <module>
getnames()
File ".\rename.py", line 13, in getnames
renames()
File ".\rename.py", line 20, in renames
rename(fname, name)
FileNotFoundError: [WinError 2] Den angivne fil blev ikke fundet: 'sans (100).png' -> 'acacia_door_top.png'
And i don't know how to fix this, i have a txt file with the new names that looks something like this
name.png
name1.png
and so on.

On way is to use zip() function if the len of both the files and arr is equal, However you could just the following if the intention is to rename all the files with names like name1.png, name2.png .. name608.png:
import os
for count, filename in enumerate(os.listdir("someDir")):
dst = "name" + str(count) + ".png"
src = 'someDir' + filename
dst = 'someDir' + dst
# rename() function will rename all the files
os.rename(src, dst)

Related

Error (WinError 123 ) when using os.rename() to rename Naruto video files

I was writing a python script to rename Naruto videos with messy titles. Here's the code:
import os
import re
def rename_files():
os.chdir(r"C:\Users\Caleb\Videos\Anime\Naruto Shippuden")
files = os.listdir('.')
for file in files:
nameRegex = re.compile(r'.?(Naruto(-?)).'
r'(Shi(p)+(u)+den)'
r'(_-_|\s-\s|\sEpisode\s|-_Season_17_Episode_| Episode |_)'
r'((\d\d\d)(-\d\d\d)?)', re.I)
mo = nameRegex.search(file)
if mo is None:
print(f'({file} Not found)')
continue
ext = os.path.splitext(file)
old_name = ext[0] + ext[1]
new_name = f"{mo.group(1).title()} {mo.group(3).title()}, Episode: {mo.group(7)}{ext[1]}"
os.rename(old_name, new_name)
rename_files()
I used os.rename() but it kept throwing the following error:
Traceback (most recent call last):
File "C:\Users\Caleb\Desktop\Python\rename_files.py", line 28, in <module>
rename_files()
File "C:\Users\Caleb\Desktop\Python\rename_files.py", line 25, in rename_files
os.rename(old_name, new_name)
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '(Hi10)_Naruto_Shippuuden_-_003_(480p)_(SD).mkv' -> 'Naruto Shippuuden, Episode: 003.mkv'
What can i do to solve this error? I've been stuck for days

How do I rename multiple files in Python, using part of the existing name?

I have a few hundred .mp4 files in a directory. When originally created their names were set as "ExampleEventName - Day 1", "ExampleEventName - Day 2" etc. thus they are not in chronological order.
I need a script to modify each of their names by taking the last 5 characters in the corresponding string and add it to the front of the name so that File Explorer will arrange them properly.
I tried using the os module .listdir() and .rename() functions, inside a for loop. Depending on my input I get either a FileNotFoundError or a TypeError:List object is not callable.
import os
os.chdir("E:\\New folder(3)\\New folder\\New folder")
for i in os.listdir("E:\\New folder(3)\\New folder\\New folder"):
os.rename(i, i[:5] +i)
Traceback (most recent call last):
File "C:/Python Projects/Alex_I/venv/Alex_OS.py", line 15, in <module>
os.rename(path + i, path + i[:6] +i)
FileNotFoundError: [WinError 2] The system cannot find the file specified:
import os, shutil
file_list = os.listdir("E:\\New folder(3)\\New folder\\New folder")
for file_name in file_list("E:\\New folder(3)\\New folder\\New folder"):
dst = "!#" + " " + str(file_name) #!# meant as an experiment
src = "E:\\New folder(3)\\New folder\\New folder" + file_name
dst = "E:\\New folder(3)\\New folder\\New folder" + file_name
os.rename(src, dst)
file_name +=1
Traceback (most recent call last):
File "C:/Python Projects/Alex_I/venv/Alex_OS.py", line 14, in <module>
for file_name in file_list("E:\\New folder(3)\\New folder\\New folder"):
TypeError: 'list' object is not callable
Some other approach:
Not based on based length ( 5 for subname )
import glob
import os
# For testing i created 99 files -> asume last 5 chars but this is wrong if you have more files
# for i in range(1, 99):
# with open("mymusic/ExampleEventName - Day {}.mp4".format(i), "w+") as f:
# f.flush()
# acording to this i will split the name at - "- Day X"
files = sorted(glob.glob("mymusic/*"))
for mp4 in files:
# split path from file and return head ( path ), tail ( filename )
head, tail = os.path.split(mp4)
basename, ext = os.path.splitext(tail)
print(head, tail, basename)
num = [int(s) for s in basename.split() if s.isdigit()][0] #get the number extracted
newfile = "{}\\{}{}{}".format(head, num, basename.rsplit("-")[0][:-1], ext) # remove - day x and build filename
print(newfile)
os.rename(mp4, newfile)
You're having multiple problems:
You're trying to increment a value that should not be incremented. Also you've created the list file_list, and thus it should not take any arguments anymore.
When using the syntax:
for x in y:
you do not have to increment the value. It will simply iterate through the list until there is no more left.
Therefore you simply have to leave out the incrementation and iterate through the list file_list.
import os, shutil
file_list = os.listdir("E:\\New folder(3)\\New folder\\New folder")
for file_name in file_list: #removed the argument, the as file_list is a list and thus not callable.
dst = "!#" + " " + str(file_name) #!# meant as an experiment
src = "E:\\New folder(3)\\New folder\\New folder" + file_name
dst = "E:\\New folder(3)\\New folder\\New folder" + file_name
os.rename(src, dst)
#file_name +=1 removed this line
Now your solution should work.

IOError: [Errno 2] No such file or directory?

I'm trying to move 220 files in Wheat to train_reuters file package,and the another files in wheat move to train_reuters test_reuters file package,but when I run the code,it give me the error,I actually have the file in the right place!how can I solve the problem?
#!/usr/bin/python
#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
import os.path
import shutil
import random
path = '/home/user1/zhouchun/lda/reuters-21578/Wheat'
targetpath1 = '/home/user1/zhouchun/lda/reuters-21578/train_reuters'
targetpath2 = '/home/user1/zhouchun/lda/reuters-21578/test_reuters'
list=random.sample(range(1, 306),220)
for i in list:
file_dir = os.path.join(path, str(i))
# print file_dir
shutil.move(file_dir, targetpath1)
files = os.listdir(path)
for file in files:
# print file
dir = os.path.join(path, file)
if dir != file_dir:
shutil.move(dir, targetpath2)
I checked your code, it is right.
Then the problem maybe:
1. you could only run your code one time, two or more times will cause this error.
2. Before you run your code, make sure all the 306 files are in Wheat directory.
I suggest using copy, but not move,then clear the train and test file before each run.
Please check the ome/user1/zhouchun/lda/reuters-21578/Wheat files number is 305.
I created a function write the random file, the code you can reference.
import random
import os
path = r'E:\temp\temp'
list= random.sample(range(1, 306), 220)
for i in list:
file_dir = os.path.join(path, str(i))
with open(file_dir, 'w') as f:
f.write('file_dir: %s' % file_dir)
f.close()
please notices the 220 in line list= random.sample(range(1, 306), 220).
After do this paste you code and change the path,
#!/usr/bin/python
#coding:utf-8
import sys
import os.path
import shutil
import random
import time
path = r'E:\temp\temp'
targetpath1 = r'E:\temp\old'
targetpath2 = r'E:\temp\new'
# move the file
list = random.sample(range(1, 306), 220)
for i in list:
file_dir = os.path.join(path, str(i))
# print file_dir
# targetpath1_dir = os.path.join(targetpath1, str(i))
shutil.move(file_dir, targetpath1)
files = os.listdir(path)
for file in files:
# print(file)
# print file
dir = os.path.join(path, file)
if dir != file_dir:
shutil.move(dir, targetpath2)
Than run the code, the error information will income.
Traceback (most recent call last):
File "D:\Python_3.5\lib\shutil.py", line 544, in move
os.rename(src, real_dst)
FileNotFoundError: [WinError 2] System can't found the file.: 'E:\\temp\\temp\\182' -> 'E:\\temp\\old\\182'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "F:/Python_Code/FaceDetect/123123.py", line 31, in <module>
shutil.move(file_dir, targetpath1)
File "D:\Python_3.5\lib\shutil.py", line 558, in move
copy_function(src, real_dst)
File "D:\Python_3.5\lib\shutil.py", line 257, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "D:\Python_3.5\lib\shutil.py", line 120, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'E:\\temp\\temp\\182'
After change the number from 220 to 305 in line list= random.sample(range(1, 306), 220), the error will disappear.
The complete code.
#!/usr/bin/python
#coding:utf-8
import sys
import os.path
import shutil
import random
import time
path = r'E:\temp\temp'
targetpath1 = r'E:\temp\old'
targetpath2 = r'E:\temp\new'
# create the random file.
list= random.sample(range(1, 306), 220)
for i in list:
file_dir = os.path.join(path, str(i))
with open(file_dir, 'w') as f:
f.write('file_dir: %s' % file_dir)
f.close()
time.sleep(1)
# move the file
list = random.sample(range(1, 306), 220)
for i in list:
file_dir = os.path.join(path, str(i))
# print file_dir
# targetpath1_dir = os.path.join(targetpath1, str(i))
shutil.move(file_dir, targetpath1)
files = os.listdir(path)
for file in files:
# print(file)
# print file
dir = os.path.join(path, file)
if dir != file_dir:
shutil.move(dir, targetpath2)
Please reference.

Issue with moving a file using shutil.move()

I am trying to move a file using the shutil module in Python. I keep getting this error:
Traceback (most recent call last):
File "<input>", line 31, in <module>
File "C:\Python27\lib\shutil.py", line 302, in move
copy2(src, real_dst)
File "C:\Python27\lib\shutil.py", line 130, in copy2
copyfile(src, dst)
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: 'MLR_Resi_Customer.txt'
I do not understand why I am getting no such file or directory. If instead of using a shutil.move(filename, new_dest) it will print the file name I am looking for.
import shutil
import os
import datetime
# set location of folders and files needed
source = '//nspinfwcipp01/BSA/marketing'
dest_cust = '//nspinfwcipp01/BSA/marketing/res_cust'
dest_pros = '//nspinfwcipp01/BSA/marketing/res_pros'
dest_win = '//nspinfwcipp01/BSA/marketing/res_win'
# create date time stamp of now
dt = str(datetime.datetime.now())
files = os.listdir(source)
print files
# create new path to storage files for old data
cust_files = os.listdir(dest_cust)
pros_files = os.listdir(dest_pros)
win_files = os.listdir(dest_win)
# new file names
new_cust = 'MLR_Resi_Customers'+dt+'.txt'
new_pros = 'MLR_Resi_Prospects'+dt+'.txt'
new_win = 'MLR_Resi_Winbacks'+dt+'.txt'
#move files from marketing folder into their own folder when after done processing
for f in files:
if (f.endswith("Customer.txt")):
print f
shutil.move(f,dest_cust)
elif (f.endswith("Prospects")):
#print f
shutil.move(f,dest_pros)
elif (f.endswith("Winbacks")):
#print f
shutil.move(f,dest_win)
##rename files in storage with data for Kalyan and Jake's Project
## rename customer file for storage
for x in cust_files:
if (x.endswith("Customers")):
#print x
new_cust = 'MLR_Resi_Customer'+dt+'.txt'
os.rename('MLR_Resi_Customers.txt', new_cust)
else:
print "no_customer_file"
## rename prospect file for storage
for x in cust_files:
if (x.endswith("Prospects")):
#print x
os.rename('MLR_Resi_Prospects.txt', new_pros)
else:
print "no_prospect_file"
## rename winback file for storage
for x in cust_files:
if (x.endswith("Winbacks")):
#print x
os.rename('MLR_Resi_Winbacks.txt', new_win)
else:
print "no_winback_file"
So I am not sure what I am doing wrong. The path to the files is correct and It seems to be able to print the file name just fine. Any help with those issues above is greatly appreciated.
Use shutil.move(glob.glob(f)[0],dest_whatever) and that should solve your problem by giving it an actual path to the file, although, if the file doesn't exist glob.glob will return an empty array.

Python: Print file names and their directory based on their file size

I want to print filenames and their directory if their filesize is more than a certain amount. I wrote one and set the bar 1KB, but it doesn't work even if there are plenty of files larger than 1KB.
import os, shutil
def deleteFiles(folder):
folder = os.path.abspath(folder)
for foldername, subfolders, filenames in os.walk(folder):
for filename in filenames:
if os.path.getsize(filename) > 1000:
print(filename + ' is inside: ' + foldername)
deleteFiles('C:\\Cyber\\Downloads')
And I got 'Nothing'!
and then I wrote codes in interactive shell, I got following error:
Traceback (most recent call last):
File "<pyshell#14>", line 3, in <module>
if os.path.getsize(filename) > 100:
File "C:\Users\Cyber\Downloads\lib\genericpath.py", line 50, in getsize
return os.stat(filename).st_size
FileNotFoundError:
I am wondering How I can fix my code.
os can't find the file without a given path, following your code, you have to re-specify the absolute path. Replace
if os.path.getsize(filename) > 1000:
with
if os.path.getsize(os.path.abspath(foldername + "/" + filename)) > 1000:
And it should work.
Replace:
deleteFiles('C:\\Cyber\\Downloads')
with
import os
a = 'c:' # removed slash
b = 'Cyber' # removed slash
c = 'Downloads'
path = os.path.join(a + os.sep, b, c)
deleteFiles(path)

Categories