Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copying a file into multiple folders using Python

I have a file Test.py. I am pasting this file into 2 different folders as shown below but I also want to change File=1 based on the folder it was pasted. For example, it is pasting Test.py into folders 1,2 with the same File=1. Instead, I want to paste Test.py into folders 1,2 with File=1 and File=2 respectively.

The content of Test.py is

File=1

The code I am using to paste is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import shutil
N=[1, 2]

src_path = r"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Multiple copy pasting\Test.py"
for i in N:
    dst_path = rf"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Multiple copy pasting\{i}"
    File={i}
    shutil.copy(src_path, dst_path)
    print('Copied')

>Solution :

Your instruction File={i} has no effect on the content of the file you copy. To change this variable in the file, you must directly edit the text, the content, of the file.

To do so, you’ll need a regex to detect the text you want to change. The expression that finds the text ‘File=’ followed by any number of digits is r"File=\d*".

So instead of copying, what you need to do is:

  • get the content of the file you want to copy
  • find the expression and replace it
  • create a new document with the value replaced.

Here is an example (you don’t need shutil here):

import re

N=[1, 2]

pattern_to_replace = re.compile(r"File=\d*")  

src_path = r"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Multiple copy pasting\Test.py"

for i in N:

    # Get content of src file
    with open(src_path, 'r') as src:
        content = src.read()

    # Modify this content
    updated_content = re.sub(pattern_to_replace, f"File={i}", content)

    # Create the new file
    dst_path = rf"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Multiple copy pasting\{i}"
   with open(dst_path, 'w') as dst:
       dst.write(updated_content)

    print('Copied')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading