J
J
joker_4fun2019-09-02 11:15:01
Python
joker_4fun, 2019-09-02 11:15:01

Python. How to rename a file based on its size?

Good day!
At work, the question arose of creating a weekly report in excel, assembled from 5 different excel files.
The problem is that all 5 files are in different folders and have different names.
Each folder has two files. Conditionally "Received.xls" and "Remains.xls".
"Remains.xls". - in each folder, always have a larger size. Let's always say more than 200kb
How to make Python go through all 5 folders and rename files larger than 200kb to 1.xls, and files less than 200kb to 2.xls.
Thanks in advance. I'm just learning Python
Upd: 5 folder name is static

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Joss Nix, 2019-09-02
@joker_4fun

import os

folder_paths = ['./']
dst_file1 = '1.xls'
dst_file2 = '2.xls'

for itemFolder in folder_paths:
    listFiles = os.listdir(itemFolder)
    for itemFiles in listFiles:
        if (itemFiles[-4:] == '.xls'):
            size_file = os.stat(itemFolder+'/'+itemFiles).st_size/1024
            if (size_file > 200):
                os.rename(itemFolder+'/'+itemFiles, itemFolder+'/'+dst_file1) 
            else:
                os.rename(itemFolder+'/'+itemFiles, itemFolder+'/'+dst_file2)

If at all in the forehead
in folder_paths you specify the paths of the necessary folders ['./', './newFolder', './newFolder2']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question