Move file to a folder or make a renamed copy if it exists in the destination folder

2024/10/13 15:18:26

I have a piece of code i wrote for school:

import ossource = "/home/pi/lab"
dest = os.environ["HOME"]for file in os.listdir(source):if file.endswith(".c")shutil.move(file,dest+"/c")elif file.endswith(".cpp")shutil.move(file,dest+"/cpp")elif file.endswith(".sh")shutil.move(file,dest+"/sh")

what this code is doing is looking for files in a source directory and then if a certain extension is found the file is moved to that directory. This part works. If the file already exists in the destination folder of the same name add 1 at end of the file name, and before the extension and if they are multiples copies do "1++". Like this: test1.c,test2.c, test3.c I tried using os.isfile(filename) but this only looks at the source directory. and I get a true or false.

Answer

To test if the file exists in the destination folder you should os.path.join the dest folder with the file name

import os                                                                       
import shutil                                                                      
source = "/home/pi/lab"
dest = os.environ["HOME"]                                                                                # Avoid using the reserved word 'file' for a variable - renamed it to 'filename' instead
for filename in os.listdir(source):                                             # os.path.splitext does exactly what its name suggests - split the name and extension of the file including the '.'name, extension = os.path.splitext(filename)                                if extension == ".c":                                                       dest_filename = os.path.join(dest, filename)                            if not os.path.isfile(dest_filename):                                      # We copy the file as isshutil.copy(os.path.join(source, filename) , dest)                  else:                       # We rename the file with a number in the name incrementing the number until we find one that is not used. # This should be moved to a separate function to avoid code duplication when handling the different file extensions                                        i = 0                                                                  dest_filename = os.path.join(dest, "%s%d%s" % (name, i,     extension)) while os.path.isfile(dest_filename):                                   i += 1                                                                                                                      dest_filename = os.path.join(dest, "%s%d%s" % (name, i, extension))shutil.copy(os.path.join(source, filename), dest_filename)    elif extension == ".cpp"...# Handle other extensions

If you want to have put the renaming logic in a separate function using glob and re this is one way:

import glob
import re
...
def rename_file(source_filename, source_ext):                                   filename_pattern = os.path.join(dest, "%s[0-9]*%s"                          % (source_filename, source_ext)) # Contains file such as 'a1.c', 'a2.c', etc...existing_files = glob.glob(filename_pattern)regex = re.compile("%s([0-9]*)%s" % (source_filename, source_ext))          # Retrieve the max of the index used for this file using regexmax_index = max([int(match.group(1))                                        for match in map(regex.search, existing_files)if match])                                                   source_full_path = os.path.join(source, "%s%s"                              % (source_filename, source_ext))            # Rebuild the destination filename with the max index + 1 dest_full_path = os.path.join(dest, "%s%d%s"                                % (source_filename,                           (max_index + 1),                           source_ext))                               shutil.copy(source_full_path, dest_full_path)...# If the file already exists i.e. replace the while loop in the else statementrename_file(name, extension)
https://en.xdnf.cn/q/118067.html

Related Q&A

Segmentation fault after removing debug printing

I have a (for me) very weird segmentation error. At first, I thought it was interference between my 4 cores due to openmp, but removing openmp from the equation is not what I want. It turns out that wh…

numpy get 2d array where last dimension is indexed according to a 2d array

I did read on numpy indexing but I didnt find what I was looking for.I have a 288*384 image, where each pixel can have a labelling in [0,15]. It is stored in a 3d (288,384,16)-shaped numpy array im.Wit…

Error sending html email with mailgun python API

I can send text email with the Mailgun python API fine:def send_simple_message(mailtext, filename=""):requests.post("https://api.mailgun.net/v3/mydomain.in/messages",auth=("api…

How to take HTML user input and query it via Python SQL?

Is there a way to take user input from HTML, and use python to run the input through to a SQL database? Does the input need to be parsed? I want the the user to be able to type in a store name, and f…

Reading and taking specific file contents in a list in python

I have a file containing:name: Sam placing: 2 quote: Ill win.name: Jamie placing: 1 quote: Be the best.and I want to read the file through python and append specific contents into a list. I want my fir…

Scipy / ctypes build-config: How to load lib?

These docs have a nice example on how to compile some external C/C++ code and load this using ctypes. This works great with manual compilation (where im controlling the names of my library which later …

Webfaction Django 1.4.1: easy_thumbnails 3.0b – Couldnt get the thumbnail error

I use easy_thumbnails and it works fine on a development machine but in production I get errors like shown below, when I use {% thumbnail photo.image 300x170 %} templatetag. Though can directly browse …

acronym replacement with its value using python

i have dictionary like that i need to replace acronyms in text with its value in dictionary i use this code but it doesnt give me the appropriate result when i test the function using acronyms("we…

Grako - How to do error handling?

How do I do error handling with Grako?EBNF (MyGrammar.ebnf):pattern = { tag | function }* ; tag = tag:( "%" name:id "%" ); function = function:("$" name:id "…

How get the softlayer storage credendials?

Im trying to get the Username,password and host IQN of a authorized Softlayer Network Storage. I used this python script, but the shell returns []import SoftLayerAPI_USERNAME = xxxAPI_KEY = yyyystorage…