Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Copying current file to destination 1

Jongskie M.

Technical User
Dec 30, 2023
24
AE
Dear Gents,

Below code shows on how to copy the recent file from source to destination, and when I compiled it just only pops & nothing happens, kindly help and reencode. thanks.

src.dest202410150039728.txt <-- this file should be copied to the destination.
src.dest20241008012256.txt
========
src_files = [f for f in os.listdir(r"D:\\LAB\\source\\")
if f.endswith('*.txt') and datetime.fromtimestamp(os.path.getmtime(f)).date() >= today]

if dest_files:
path = r'D:\\LAB\\dest\\{short_month} {year}'

print("File detected {dest_files}")
shutil.sleep(1)

for ste in dest_files:
src_path = r'D:\\LAB\\dest\\{ste}'
dest_path = os.path.join(path)
print("Copying File" + ste)
shutil.copy(src_path, dest_path)

input("Filecheck")
os.startfile(path)

else:
print("File is unavailable!")
 
Offhand, I see these problems:

  1. "*" is an illegal character in a file name, so there can never be any files that .endswith('*.txt') so src_files will always be empty.
  2. today is not defined.
  3. dest_files is not defined
  4. Since you're using r strings you don't need to escape the slashes in the paths. Having double slashes may cause unexpected behavior.
  5. You never use the user's input from input("Filecheck") for anything.
 
There are a few issues in the code that could be causing it not to function...

  1. The wildcard in endswith(): The function endswith('*.txt') won't work as expected because endswith() looks for the exact string. You should remove the * and use just .txt.
  2. Incorrect use of variables inside strings: In Python, variables inside strings need to be formatted properly. For example, '{short_month} {year}' will not automatically replace with the values of those variables unless you use an f-string or the .format() method.
  3. Not sure about shutil.sleep(). I use use time.sleep().
  4. The dest_files variable is not defined: You seem to be using dest_files without defining it. I believe you meant to use src_files in the loop.
Here's how I would write the code.

Code:
import os
import shutil
from datetime import datetime
import time

# Define the source directory
source_dir = r"D:\\LAB\\source\\"

# Get today's date
today = datetime.now().date()

# Get the list of recent files (txt files modified today)
src_files = [f for f in os.listdir(source_dir)
             if f.endswith('.txt') and datetime.fromtimestamp(os.path.getmtime(os.path.join(source_dir, f))).date() >= today]

if src_files:
    # Define destination path
    short_month = today.strftime('%b')  # Example: 'Oct'
    year = today.year
    dest_dir = f"D:\\LAB\\dest\\{short_month} {year}"

    # Create the destination directory if it doesn't exist
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)

    print(f"File(s) detected: {src_files}")
    time.sleep(1)

    # Copy each file to the destination
    for file in src_files:
        src_path = os.path.join(source_dir, file)
        dest_path = os.path.join(dest_dir, file)
        print(f"Copying File: {file}")
        shutil.copy(src_path, dest_path)

    input("Press Enter to check the files...")
    os.startfile(dest_dir)

else:
    print("No files available!")
 
There are a few issues in the code that could be causing it not to function...

  1. The wildcard in endswith(): The function endswith('*.txt') won't work as expected because endswith() looks for the exact string. You should remove the * and use just .txt.
  2. Incorrect use of variables inside strings: In Python, variables inside strings need to be formatted properly. For example, '{short_month} {year}' will not automatically replace with the values of those variables unless you use an f-string or the .format() method.
  3. Not sure about shutil.sleep(). I use use time.sleep().
  4. The dest_files variable is not defined: You seem to be using dest_files without defining it. I believe you meant to use src_files in the loop.
Here's how I would write the code.

Code:
import os
import shutil
from datetime import datetime
import time

# Define the source directory
source_dir = r"D:\\LAB\\source\\"

# Get today's date
today = datetime.now().date()

# Get the list of recent files (txt files modified today)
src_files = [f for f in os.listdir(source_dir)
             if f.endswith('.txt') and datetime.fromtimestamp(os.path.getmtime(os.path.join(source_dir, f))).date() >= today]

if src_files:
    # Define destination path
    short_month = today.strftime('%b')  # Example: 'Oct'
    year = today.year
    dest_dir = f"D:\\LAB\\dest\\{short_month} {year}"

    # Create the destination directory if it doesn't exist
    if not os.path.exists(dest_dir):
        os.makedirs(dest_dir)

    print(f"File(s) detected: {src_files}")
    time.sleep(1)

    # Copy each file to the destination
    for file in src_files:
        src_path = os.path.join(source_dir, file)
        dest_path = os.path.join(dest_dir, file)
        print(f"Copying File: {file}")
        shutil.copy(src_path, dest_path)

    input("Press Enter to check the files...")
    os.startfile(dest_dir)

else:
    print("No files available!")
Thanks SoftwareRT
 
Hi SoftwareRT,

from the code below, kindly insert a code validation if the file is exist then it prints file is already existing from the destination path.
===
# Create the destination directory if it doesn't exist
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)

print(f"File(s) detected: {src_files}")
time.sleep(1)

==
regards,
 

Part and Inventory Search

Sponsor

Back
Top