Renaming files (while counting the number) - python

I'm currently trying to write a python script to rename a bunch of files. The file is named like this: [Name][Number]-[Number]. To give a specific example: milk-00-00. The next file is milk-00-01, then 02, 03 until X. After that milk-01-00 starts with the same pattern.
What I need to do is to switch 'milk' into a number and replace the '-XX-XX' by '-01', '02', ...
I hope you guys get the idea. The current state of my code is pretty poor, it was hard enough to get it this far though. It looks like this and with this I'm at least able to replace something. I'll also manage to get rid of the 'milk' with the help of google. However, if there is an easier way, I'd really appreciate a push in the right direction!
import os
import sys
path = 'C:/Users/milk/Desktop/asd'
i=00
for filename in os.listdir(path):
if filename.endswith('.tiff'):
newname = filename.replace('00', 'i')
os.rename(filename,newname)
i=i+1

You can use the format function
temp = (' ').join(filename.split('.')[:-1])
os.rename(filename, '10{}-{}.tiff'.format(temp.split('-')[-2],temp.split('-')[-1]))
Since filename has the .tiff extension this program first creates a version of filename without the extension - temp - and then creates new names from that.

os.rename(filename, '1000-%02d.tiff' % i)
i += 1

Related

Re-Naming Files as they are being opened in Python For Loop

I'm trying to create a program that will read in multiple .txt files and rename them in one go. I'm able to read them in, but I'm falling flat when it comes to defining them all.
First I tried including an 'as' statement after the open call in my loop, but the files kept overwriting each other since it's only one name I'm defining. I was thinking I could read them in as 'file1', 'file2', 'file3'... etc
Any idea on how I can get this naming step to work in a for loop?
import os
os.chdir("\\My Directory")
#User Inputs:
num_files = 3
#Here, users' actual file names in their directory would be 'A.txt',
'B.txt', 'C.txt'
filenames = [A, B, C]
j = 1
for i in filenames:
while j in range(1,num_files):
open(i + ".txt", 'r').read().split() as file[j]
j =+ 1
I was hoping that each time it read in the file, it would define each one as file#. Clearly, my syntax is wrong because of the way I'm indexing 'file'. I've tried using another for loop in the for loop, but that gave me a syntax error as well. I'm really new to python and programming logic in general. Any help would be much appreciated.
Thank you!
You should probably use the rename() function in the os module. An example could be:
import os
os.rename("stackoverflow.html", "xyz.html")
stack overflow.html would be the name you want to call the file and xyz.html would be the current name of the file/the destination of the file. Hope this helps!

Delete every 1 of 2 or 3 files on a folder with Python

What I'm trying to do is to write a code that will delete a single one of 2 [or 3] files on a folder. I have batch renamed that the file names are incrementing like 0.jpg, 1.jpg, 2.jpg... n.jpg and so on. What I had in mind for the every single of two files scenario was to use something like "if %2 == 0" but couldn't figure out how actually to remove the files from the list object and my folder obviously.
Below is the piece of NON-WORKING code. I guess, it is not working as the file_name is a str.
import os
os.chdir('path_to_my_folder')
for f in os.listdir():
file_name, file_ext = os.path.splitext(f)
print(file_name)
if file_name%2 == 0:
os.remove();
Yes, that's your problem: you're trying to use an integer function on a string. SImply convert:
if int(file_name)%2 == 0:
... that should fix your current problem.
Your filename is a string, like '0.jpg', and you can’t % 2 a string.1
What you want to do is pull the number out of the filename, like this:
name, ext = os.path.splitext(filename)
number = int(name)
And now, you can use number % 2.
(Of course this only works if every file in the directory is named in the format N.jpg, where N is an integer; otherwise you’ll get a ValueError.)
1. Actually, you can do that, it just doesn’t do what you want. For strings, % means printf-style formatting, so filename % 2 means “find the %d or similar format spec in filename and replace it with a string version of 2.
Thanks a lot for the answers! I have amended the code and now it looks like this;
import os
os.chdir('path_to_the_folder')
for f in os.listdir():
name, ext = os.path.splitext(f)
number = int(name)
if number % 2 == 0:
os.remove()
It doesn't give an error but it also doesn't remove/delete the files from the folder. What in the end I want to achieve is that every file name which is divisible by two will be removed so only 1.jpg, 3.jpg, 5.jpg and so on will remain.
Thanks so much for your time.
A non-Python method but sharing for future references;
cd path_to_your_folder
mkdir odd; mv *[13579].png odd
also works os OSX. This reverses the file order but that can be re-corrected easily. Still want to manage this within Python though!

access a file with not fully known filename in python

I have a huge database of files whose names are like:
XYZ-ABC-K09235D1-20151220-5H1E2H4A.txt
XYZ-ABC-W8D2S5G5-20151225-HG2EK4GE.txt
XYZ-ABC-ME2C5K32-20160206-DD8BA4R6.txt
etc...
Names have all the same structure:
'XYZ-ABC-' + 8 random char + '%y%m%d' + 8 random char + '.txt'
Now, I need to open a file, given the date. The point is that, I don't know the exact name of the file, as there are some random chars within. For instance, for datetime 12/05/2014 I know the filename will be something like
XYZ-ABC-????????-20140512-????????.txt
but I don't know the exact name when using f.open command. What could be the best way to do this? (I thought about first creating a list with all filenames, but I don't know whether it's a good technique or if it's better to use something like glob...). Thank you in advance.
You can use following code
import os
fileName = [filename for filename in os.listdir('.') if filename.startswith("prefix") and 'otherstring' in filename]
Hope this helps !

Python - automaticly zip specific folders/files

I have been getting into Python lately and have come across a problem wich i think i could solve using it.
I have a USB stick with a lot of folders in there, the folders each contain the following:
/HTML5/
/Images/
foldername.html
foldername.ofp
preview.html
profile.xml
Now, i have to create a zip file of each folder, but only containing the Images folder and the profile.xml file. There is 40ish folders in there and there will be more in the future.
Here is the final code:
# Script to zip Foldername/Images/ and Foldername/profile.xml to Foldername.zip
import os
import zipfile
dirname = "D:\\testdir"
for schoen in os.listdir(dirname):
print schoen
myZipFile = zipfile.ZipFile(schoen+".zip", "w" )
for f in os.listdir(os.path.join(dirname, schoen)):
print f
if f == "Profile.xml":
print "Found profile.xml"
myZipFile.write(schoen + "\\" + f, f)
elif f == "Images":
print "Found Images"
myZipFile.write(schoen + "\\" + f, f)
myZipFile.close()
Many thanks,
Grootie
Instead of finding random code and trying to guess what it might mean and what you should change, why not look it up in the documentation?
The parameters to ZipFile.write are:
ZipFile.write(filename, arcname=None, compress_type=None)
So your code copies the file named profile.xml into the archive under the name images\\test.py. Is that really what you want? I doubt it. But I'm not sure what you do want. You need to figure that out, in terms you could explain to an idiot (because computers are idiots). Then the docs—or SO, if you get confused by the docs—can help you translate that explanation into the appropriate code.

Trying to create a replay feature for a Turn-based game (very newbie)

I'm currently playing a trading card game called Hearthstone which is made by blizzard. The game is pretty good, but lacks basic features that any game that calls itself "competitive" should have, like stat tracking and replay.
So as I said in the title, I'm trying to create a (very crude and poorly done) script that let's me record every match I play. Due to my lack of programming skills, 80% of the script is just a bunch of code that I borrowed from all sorts of places and adapted to make it do what I wanted.
The idea is to make it work like this:
I take a picture of every turn I play. It might become annoying, but I do not dare to think about implementing OCR as to make the script take a picture at the start of every turn by itself. Would be awesome but I just can't do it...
The game sends every picture to the desktop (no need to code that).
At the end of the game I run the script
2.1 Every match is going to have a numbered folder so the script creates that. The folders are going to be called "Match1", "Match2", etc. You can see how poorly written that is because I made it on my own :P
import sys
import os
import shutil
def checkFolder():
os.path.join('D:\Hearthstone\Replays\Match1')
matchNumber=1
while os.path.exists("D:\\Hearthstone\\Replays\\Match"+ str(matchNumber)) is True:
matchNumber=matchNumber + 1
else:
os.makedirs("D:\Hearthstone\Replays\Match"+str(matchNumber))
2.2 Script sends the photos from Desktop to the recently created folder. The Problem is that I do not know how to make the script change the destination folder to the newest folder created. I did not write this part of the code, i merely adapted it. Source: http://tinyurl.com/srcbh
folder = os.path.join('C:\\Users\\Felipe\\', 'Desktop') # Folder in which the images are in.
destination = os.path.join('D:\\Hearthstone\\Replays\\', 'match9999') #**Destination needs to be the newest folder and I dont know how to implement that...
extmove = 'png' # The extension you wish to organize.
num = 0 # Variable simply to use after to count images.
for filename in os.listdir(folder): #Run through folder.
extension = filename.split(".")[-1] # This strips the extensions ready to check and places into the extension
if extension == extmove: # If statement. If the extension of the file matches the one set previously then..
shutil.move(folder + "\\" + filename, destination) # Move the file from the folder to the destination folder. Also previously set.
num = num + 1
print(num)
print (filename, extension)
And that's it! I need help with step 2.2. I'd certainly appreciate the help!
Now, the reason I made such a big post is because I wanted to expose my idea and hopefully inspire someone to take on a similar project seriously. Hearthstone has thousands of players that could benefit from it, not to mention that this seems to be a fairly easy task to someone with more experience.
Ok, I finally got it to work!
import sys
import os
import shutil
def sendPhotos():
matchNumber=1
photos_dest = "D:\\Hearthstone\\Replays\\Match"
while os.path.exists(photos_dest+ str(matchNumber)): #creates the name of the folder "Match1", "Match2", etc.
matchNumber=matchNumber + 1
else:
photos_destination = photos_dest+str(matchNumber)
os.makedirs(photos_destination)
for files in os.listdir('C:\\Users\\Felipe\\Desktop'):#only png files are moved
if files.endswith(".png"):
shutil.move(files, photos_destination)
sendPhotos()
Thank you to those who gave me some answers! I really appreciated it!
Well, first off, the fact that you identified a problem and put together a solution shows that you certainly don't lack programming skills. Give yourself some credit. You just need more practice. :)
This should be better, I haven't run it, so there might be some errors :P
def checkFunction(base_dir='D:\\Hearthstone\\Replays\\'): #set this as a parameter with a default
match_number = 1
if os.path.exists(base_dir): #if the base directory doesn't exist you'll have a bad time
while os.path.exists(os.path.join(base_dir, 'Match{0}'.format(match_number)))
match_number += 1
new_dir = os.path.join(base_dir, 'Match{0}'.format(match_number))
os.makedirs(new_dir)
return new_dir
For the function checkFolder, I suggest having it return the new directory name (as above). You'll also need to indent all the lines below it so python knows those lines are part of that function (this might just be a formatting issue on SO though).
Then, once the checkFolder function is working properly, all you have the change in 2.2 is:
destination = checkFolder()
This sees which matches are in the folder and takes the lowest number for the folder.
folder = os.path.join('C:\\Users\\Felipe\\', 'Desktop') # Folder in which the images are in.
recorded_matches_location = 'D:\\Hearthstone\\Replays\\'
match_number = 1
match_name = 'match1'
while match_name in os.listdir(recorded_matches_location):
match_number = 1 + match_number
match_name = 'match' + str(match_number) # corrected it! there must be a string and not a variable
destination = os.path.join(recorded_matches_location, match_name) #**Destination needs to be the newest folder and I dont know how to implement that...
extmove = 'png' # The extension you wish to organize.
num = 0 # Variable simply to use after to count images.
for filename in os.listdir(folder): #Run through folder.
extension = filename.split(".")[-1] # This strips the extensions ready to check and places into the extension
if extension == extmove: # If statement. If the extension of the file matches the one set previously then..
shutil.move(folder + "\\" + filename, destination) # Move the file from the folder to the destination folder. Also previously set.
num = num + 1
print(num)
print (filename, extension)

Categories

Resources