Python Forum
Thread Rating:
  • 2 Vote(s) - 1.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
leading zeros
#1
Hi,

A wrote a script that moves files into folders according to the files creation time, but I could not figure out how to add a leading zero to the folders name. I'd like it this way: 2017-01-18, not 2017-1-18.

import os, time, shutil

os.chdir('.')

for f in os.listdir('.'):
    file_creation_time = time.gmtime(os.path.getmtime(f))
    dir_creation_time = str(file_creation_time.tm_year) + '-' + str(file_creation_time.tm_mon) + '-' + str(file_creation_time.tm_mday)

    if not os.path.isdir(dir_creation_time):
        os.mkdir(dir_creation_time)
    if '.py' in f:
        continue

    else:
        try:
            shutil.move(f, dir_creation_time)
        except:
            pass
And I'd like a more elegant way of excluding the the script, but sys.argv[0] returns the full path, but I only need the script name.
I also wanted the first argument to be the folder path on which folder the script should run, i tried this at the beginning:

dir = sys.argv[1]

os.chdir(dir)
But it didn't work. I'd really like to invoke the script by cron, with an argument on which folder should it run...

Thanks

Zoli
Reply
#2
replace
file_creation_time = time.gmtime(os.path.getmtime(f))
dir_creation_time = str(file_creation_time.tm_year) + '-' + str(file_creation_time.tm_mon) + '-' + str(file_creation_time.tm_mday)
with

dir_creation_time = time.strftime('%Y-%m-%d', time.gmtime(os.path.getmtime(f)))
Reply
#3
Lovely, thanks!
Reply
#4
Hi,

I have some flac files without leading zeros:

https://pastebin.com/cEVpqkSu

I did this code:
import os

folder = "Scott.Ross_Goldberg.Variations"


for i in os.listdir(folder):
    filename, extension = (os.path.splitext(i))
    filenumber = (filename.split('.')[0].zfill(2))
    filename = (filename.split('.')[1])
    new_filename =('{}.{}{}'.format(filenumber, filename, extension))
    print(new_filename)
    #os.rename(i, new_filename)
Interestingy if I print them, they look good, but if I would like to rename them, the scripts gives me an error:

Error:
Traceback (most recent call last):   File "/home/zoli/PycharmProjects/leadingZeros/inserter.py", line 12, in <module>     os.rename(i, new_filename) FileNotFoundError: [Errno 2] No such file or directory: '5. Variatio 4 a 1 Clav.flac' -> '05. Variatio 4 a 1 Clav.flac'
Obviously I did some mistake, could you help me out? First I was suspicious of whitespace characters in filenames, but i don't think that's the case. The files are there in the folder.
Reply
#5
(Jan-18-2017, 06:38 PM)kerzol81 Wrote:
os.chdir('.')
Is absolutely redundant - you are already in the target directory
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#6
I tried this, it doesn't solve it. Thanks though. I know it's not needed to change into the directory
Reply
#7
You either need to run the program in the Scott.Ross_Goldberg.Variations folder, or change directories to that folder.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#8
I figured it out. The error was that the folder var needed a full path...

import os

folder = "/home/zoli/PycharmProjects/leadingZeros/Scott.Ross_Goldberg.Variations/"
os.chdir(folder)

for i in os.listdir(folder):
   filename, extension = (os.path.splitext(i))
   filenumber = (filename.split('.')[0].zfill(2))
   filename = (filename.split('.')[1])
   new_filename =('{}.{}{}'.format(filenumber, filename, extension))
   #print(new_filename)
   os.rename(i, new_filename)
Thanks for your help, I really needed to change into that directory. What I don't understund is, that if the script was able to change into that dir, and print the corrected filenames, why it needed an absolute path for the renaming.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Removing leading whitespaces palladium 1 731 Mar-24-2023, 04:15 PM
Last Post: bowlofred
  Removing leading\trailing spaces azizrasul 8 2,725 Oct-23-2022, 11:06 PM
Last Post: azizrasul
  How to retrieve records in a DataFrame (Python/Pandas) that contains leading or trail mmunozjr 3 1,765 Sep-05-2022, 11:56 AM
Last Post: Pedroski55
  -i option changes sys.path (removes leading empty string '') markanth 6 1,994 Aug-26-2022, 09:27 PM
Last Post: markanth
  remove zeros at the end of a number Frankduc 7 2,180 Feb-25-2022, 03:48 PM
Last Post: Frankduc
  Solving for zeros of an equation! fmitchell17 0 1,841 Apr-05-2021, 07:49 PM
Last Post: fmitchell17
  Dataframe Removes Zeros JoeDainton123 2 4,404 Sep-17-2020, 12:47 PM
Last Post: scidam
  How to keep leading zeros with pandas? eeps24 1 6,580 May-20-2020, 07:51 PM
Last Post: deanhystad
  Cancelling 'open directory' leading to crash Fairbz_ 1 2,191 May-08-2020, 03:14 PM
Last Post: DPaul
  leading zero number formatting RedSkeleton007 3 3,946 Jan-27-2019, 04:56 PM
Last Post: RedSkeleton007

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020