Renaming files with python to 1.jpg, 2.jpg, etc - python

First I would like to say I want to do this in python 2.7!
Hi, I have a folder full of images named 1.jpg, 2.jpg, 3.jpg, etc. All the way up to 600.jpg.
I would like to rename them 600 higher, so 601.jpg, 602.jpg, 603.jpg, etc. All the way up to 1200.jpg.
I am honestly not quite sure where to start, so any help would be useful. It doesn't seam like it should be hard but I was not able to name them in ascending order. The best I got was 601.jpg, 601.jpg, and it was the same for every file.
This is what I have currently, it's been altered a few times, and now all I get is an error.
import os
path = '/Users/antse/OneDrive/Documents/Instagram/set_2'
files = os.listdir(path)
i = 601
for file in files:
os.rename(os.path.join(path, file), os.path.join(path, str(i)+'.jpg'))
i = i+1

One of the problems with your approach is that listdir doesn't come back in order from 1.jpg ..., and it includes any other files or subdirectories. But there is no need to list the directory - you already know the pattern of what you want to change and its a hassle to deal with other files that may be there.
import os
path = '/Users/antse/OneDrive/Documents/Instagram/set_2'
for i in range(1, 601):
old_name = os.path.join(path, '{}.jpg'.format(i))
new_name = os.path.join(path, '{}.jpg'.format(i+600))
try:
os.rename(old_name, new_name)
except OSError as e:
print 'could not rename', old_name, e

Related

Python to rename files in a directory/folder to csv

I have written a small script to hopefully iterate through my directory/folder and replace act with csv. Essentially, I have 11 years worth of files that have a .act extension and I just want to replace it with .csv
import os
files = os.listdir("S:\\folder\\folder1\\folder2\\folder3")
path = "S:\\folder\\folder1\\folder2\\folder3\\"
#print(files)
for x in files:
new_name = x.replace("act","csv")
os.rename(path+x,path+new_name)
print(new_name)
When I execute this, it worked for the first five files and then failed on the sixth with the following error:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'S:\\folder\\folder1\\folder2\\folder3\\file_2011_06.act' -> 'S:\\folder\\folder1\\folder2\\folder3\\file_2011_06.csv'
When I searched for "S:\folder\folder1\folder2\folder3\file_2011_06.act" in file explorer, the file opens. Are there any tips on what additional steps I can take to debug this issue?
Admittedly, this is my first programming script. I'm trying to do small/minor things to start learning. So, I likely missed something... Thank you!
In your solution, you use string's replace to replace "act" by "csv". This could lead to problems if your path contains "act" somewhere else, e.g., S:\\facts\\file_2011_01.act would become S:\\fcsvs\\file_2011_01.act and rename will throw a FileNotFoundError because rename cannot create folders.
When dealing with file names (e.g., concatenating path fragments, extracting file extensions, ...), I recommend using os.path or pathlib instead of direct string manipulation.
I would like to propose another solution using os.walk. In contrast to os.listdir, it recursively traverses all sub-directories in a single loop.
import os
def act_to_csv(directory):
for root, folders, files in os.walk(directory):
for file in files:
filename, extension = os.path.splitext(file)
if extension == '.act':
original_filepath = os.path.join(root, file)
new_filepath = os.path.join(root, filename + '.csv')
print(f"{original_filepath} --> {new_filepath}")
os.rename(original_filepath, new_filepath)
Also, I'd recommend to first backup your files before manipulating them with scripts. Would be annoying to loose data or see it becoming a mess because of a bug in a script.
import os
folder="S:\\folder\\folder1\\folder2\\folder3\\"
count=1
for file_name in os.listdir(folder):
source = folder + file_name
destination = folder + str(count) + ".csv"
os.rename(source, destination)
count += 1
print('All Files Renamed')
print('New Names are')
res = os.listdir(folder)
print(res)

How can I copy files from a folder into multiple folders

I have 130 files in a folder source and I want to copy each files in a single folder 001, 002, 003 ... 130 (all these 130 folders are located in destination folder).
So that every folder contain just one file.
I came up with this but probably it's a bit messy and redundant... and mostly it doesn't work.
import shutil
import os
source = '/Users/JohnCN/photo_database/mugshot_frontal/'
files = os.listdir(source)
for i in files:
for fold in range(1,131):
if fold<10:
destination = "/Users/JohnCN/photo_DBsorted/00%s" %fold
shutil.move(source+i, destination)
elif fold in range(10,100):
destination = "/Users/JohnCN/photo_DBsorted/0%s" %fold
shutil.move(source+i, destination)
else:
destination = "/Users/JohnCN/photo_DBsorted/%s" %fold
shutil.move(source+i, destination)
I would do it the following way:
import shutil
import os
source = '/Users/JohnCN/photo_database/mugshot_frontal/'
files = os.listdir(source)
for idx, f in enumerate(files):
destination = '/Users/JohnCN/photo_DBsorted/{d:03d}'.format(d=(idx + 1))
shutil.move(source + f, destination)
So, what does it do?
for idx, f in enumerate(files): counts the files while looping, so you know the index of the file. To get the destination, the idx is used as directory name. I assume you know the method format, {d:03d} simply says, that the value d is assigned to should be 3 characters long, the value is an integer and it's padded with zeros (e.g. 003). Of course, this code assumes that you do not have 1000+ files, in that case, just increase the number of zeroes. You could for example calculate the log10-value of the number of files to get the number of zeros you have to add.
First of all, I would rather use shutil.copy if I wanted to copy the files, but not to move. Though, the main idea does not depend on it. Also you don't need no if statements here as well as the inner cycle:
files = os.listdir(source)
for i in range(len(files)):
file = os.path.join(source, files[i])
shutil.copy(file, os.path.join(source, '%03d'%i, files[i])

Adding extension to multiple files (Python3.5)

I have a bunch of files that do not have an extension to them.
file needs to be file.txt
I have tried different methods (didn't try the complicated ones since I am just learning to do a bit of advanced python).
here is one that I tried:
import os
pth = 'B:\\etc'
os.chdir(pth)
for files in os.listdir('.'):
changeName = 'files{ext}'.format(ext='.txt')
I tried the append, replace and rename methods as well and it didn't work for me. or those don't work in the 1st place with what I am trying to do?
What am I missing or doing wrong?.
You need os.rename. But before that,
Check to make sure they aren't folders (thanks, AGN Gazer)
Check to make sure those files don't have extensions already. You can do that with os.path.splitext.
import os
root = os.getcwd()
for file in os.listdir('.'):
if not os.path.isfile(file):
continue
head, tail = os.path.splitext(file)
if not tail:
src = os.path.join(root, file)
dst = os.path.join(root, file + '.txt')
if not os.path.exists(dst): # check if the file doesn't exist
os.rename(src, dst)

Copy files from multiple directories into one directory using Python

What is the easiest way to copy files from multiple directories into just one directory using python? To be more clear, I have a tree that looks like this
+Home_Directory
++folder1
-csv1.csv
-csv2.csv
++folder2
-csv3.csv
-csv4.csv
and I want to put csv1,csv2,...etc all into some specified directory without the folder hierarchy.
+some_folder
-csv1.csv
-csv2.csv
-csv3.csv
-csv4.csv
Some solutions I have looked at:
Using shutil.copytree will not work because it will preserve the file structure which is not what I want.
The code I am playing with is very similar to what is posted in this question:
copy multiple files in python
the problem is that I do not know how to do this iteratively. Presumably it would just be another for loop on top of this but I am not familiar enough with the os and shutil libraries to know exactly what I am iterating over. Any help on this?
This is what I thought of. I am assuming you are only pulling csv files from 1 directory.
RootDir1 = r'*your directory*'
TargetFolder = r'*your target folder*'
for root, dirs, files in os.walk((os.path.normpath(RootDir1)), topdown=False):
for name in files:
if name.endswith('.csv'):
print "Found"
SourceFolder = os.path.join(root,name)
shutil.copy2(SourceFolder, TargetFolder) #copies csv to new folder
Edit: missing a ' at the end of RootDir1. You can also use this as a starting guide to make it work as desired.
import glob
import shutil
#import os
dst_dir = "E:/images"
print ('Named explicitly:')
for name in glob.glob('E:/ms/*/*/*'):
if name.endswith(".jpg") or name.endswith(".pdf") :
shutil.copy(name, dst_dir)
print ('\t', name)
You can use it to move all subfolders from the same to a different directory to wherever you want.
import shutil
import os
path=r'* Your Path*'
arr = os.listdir(path)
for i in range(len(arr)):
source_dir=path+'/'+arr[i]
target_dir = r'*Target path*'
file_names = os.listdir(source_dir)
for file_name in file_names:
shutil.move(os.path.join(source_dir, file_name), target_dir)

Moving into a directory without knowing its name

Im a noob to python and I am trying to complete this simple task. I want to access multiple directories one by one that are all located inside one directory. I do not have the names of the multiple directories. I need to enter into the directory, combine some files, move back out of that directory, then into the next directory, combine some files, move back out of it, and so on........ I need to make sure I dont access the same directory more than once.
I looked around and tried various commands and nothing yet.
try using something like the following piece of code.:
import os, fnmatch
def find_files(directory, pattern):
for root, dirs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
filename = os.path.join(root, basename)
yield filename
use it something like this:
for filename in find_files('/home/', '*.html')
# do something
Sometimes I find glob to be useful:
from glob import glob
import os
nodes = glob('/tmp/*/*')
for node in nodes:
try:
print 'now in directory {}'.format(os.path.dirname(node))
with open(node, 'r') as f:
# Do something with f...
print len(f.read())
except IOError: # Because node may be a directory, which we cannot 'open'
continue

Categories