file_names = [name.strip() for name in file_names]
if not os.path.exists(source_folder):
print("Source folder not found!")
return
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
print(f"Destination folder '{destination_folder}' created.")
for dirpath, _, filenames in os.walk(source_folder):
for filename in filenames:
if filename in file_names:
file_path = os.path.join(dirpath, filename)
dest_file_path = os.path.join(destination_folder, filename)
if not os.path.exists(dest_file_path):
shutil.copy2(file_path, dest_file_path)
print(f"File '{filename}' copied successfully from '{file_path}'!")
elif filename.endswith('.zip'):
zip_path = os.path.join(dirpath, filename)
extract_and_copy_files(zip_path, destination_folder, file_names)
simply write a new code to take path of a folder and a excel file path and tell which files are missing form the folder fron the excel mentioend ....one folder having pdfs and one excel hving filename column compare them and tell the reson
Assistant
User
import os
import pandas as pd
def find_missing_files(folder_path, excel_file_path):
try:
# Read the file names from the Excel file
df = pd.read_excel(excel_file_path)
code
Assistant
try:
temp_extract_dir = zip_path + "_extracted"
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(temp_extract_dir)
print(f"Extracted '{zip_path}' to '{temp_extract_dir}'")
for dirpath, _, filenames in os.walk(temp_extract_dir):
for filename in filenames:
if filename in file_names:
file_path = os.path.join(dirpath, filename)
dest_file_path = os.path.join(destination_folder, filename)
if not os.path.exists(dest_file_path):
shutil.copy2(file_path, dest_file_path)
print(f"File '{filename}' copied successfully from extracted '{file_path}'!")
else:
print(f"File '{filename}' already exists in the destination folder.")
except Exception as e:
print(f"Error extracting '{zip_path}': {e}")
finally:
if os.path.exists(temp_extract_dir):
shutil.rmtree(temp_extract_dir)
print(f"Temporary extraction directory '{temp_extract_dir}' has been removed.")
def read_file_names_from_excel(excel_file_path):
code
"""Read the file names from the specified Excel sheet."""
try:
df = pd.read_excel(excel_file_path)
return df['File Name'].dropna().tolist()
except Exception as e:
print(f"Error reading Excel file: {e}")
return []
if name == "main":
code
source_folder = r"D:\GILSIL Vs DFCCIL All FIles"
destination_folder = r"D:\GILSILISSUE1"
excel_file_path = r"D:\GILSILISSUE1\201ISSUE1.xlsx"
file_names = read_file_names_from_excel(excel_file_path)
if file_names:
copy_files(source_folder, destination_folder, file_names)
else:
print("No file names found in the Excel file.")
in this my excel have 555 row files the new folder only habve 506 files in it .....so write a script to cosschck the files which re not fetched and the reason for that also
To cross-check which files from your Excel list were not copied to the destination folder and to identify the reasons behind that, you can enhance your existing script. Here’s a modified version that checks for files that were expected to be present but were not found in the destination folder:
python
import os
import shutil
import pandas as pd
import zipfile
def copy_files(source_folder, destination_folder, file_names):
file_names = [name.strip() for name in file_names]
copied_files = []
not_found = []
already_exists = []
if not os.path.exists(source_folder):
print("Source folder not found!")
return
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
print(f"Destination folder '{destination_folder}' created.")
for dirpath, _, filenames in os.walk(source_folder):
for filename in filenames:
if filename in file_names:
file_path = os.path.join(dirpath, filename)
dest_file_path = os.path.join(destination_folder, filename)
if not os.path.exists(dest_file_path):
shutil.copy2(file_path, dest_file_path)
print(f"File '{filename}' copied successfully from '{file_path}'!")
copied_files.append(filename)
else:
already_exists.append(filename)
elif filename.endswith('.zip'):
zip_path = os.path.join(dirpath, filename)
extract_and_copy_files(zip_path, destination_folder, file_names)
# Compare expected files vs copied or existing
for expected_file in file_names:
if expected_file not in copied_files and expected_file not in already_exists:
not_found.append(expected_file)
return not_found, copied_files, already_exists
def extract_and_copy_files(zip_path, destination_folder, file_names):
try:
temp_extract_dir = zip_path + "_extracted"
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall(temp_extract_dir)
print(f"Extracted '{zip_path}' to '{temp_extract_dir}'")
for dirpath, _, filenames in os.walk(temp_extract_dir):
for filename in filenames:
if filename in file_names:
file_path = os.path.join(dirpath, filename)
dest_file_path = os.path.join(destination_folder, filename)
if not os.path.exists(dest_file_path):
shutil.copy2(file_path, dest_file_path)
print(f"File '{filename}' copied successfully from extracted '{file_path}'!")
except Exception as e:
print(f"Error extracting '{zip_path}': {e}")
finally:
if os.path.exists(temp_extract_dir):
shutil.rmtree(temp_extract_dir)
print(f"Temporary extraction directory '{temp_extract_dir}' has been removed.")
def read_file_names_from_excel(excel_file_path):
"""Read the file names from the specified Excel sheet."""
try:
df = pd.read_excel(excel_file_path)
return df['File Name'].dropna().tolist()
except Exception as e:
print(f"Error reading Excel file: {e}")
return []
if __name__ == "__main__":
source_folder = r"D:\GILSIL Vs DFCCIL All FIles"
destination_folder = r"D:\GILSILISSUE1"
excel_file_path = r"D:\GILSILISSUE1\201ISSUE1.xlsx"
file_names = read_file_names_from_excel(excel_file_path)
if file_names:
not_found_files, copied_files, existing_files = copy_files(source_folder, destination_folder, file_names)
# Report the results
if not_found_files:
print(f"The following files were not found and weren't copied: {not_found_files}")
else:
print("All files were copied successfully.")
if existing_files:
print(f"The following files already existed in the destination folder: {existing_files}")
else:
print("No file names found in the Excel file.")
Explanation of Updates:
Tracking Variables:
Added lists (copied_files, not_found, already_exists) to track copied files, files that were not found, and those that already existed in the destination folder.
Comparison Logic:
After attempting to copy files, the script compares the list of expected file names from Excel with those that were actually copied or already existed.
Reporting:
At the end, the script reports the files that were not found and those that already existed instead of just copying.
This enhanced script will:
Attempt to copy files listed in the Excel file from the specified source directory.
Inform you specifically about files that were not copied because they were either missing or already present in the destination directory.
Sure! Below is a simple Python script that takes the path of a folder and an Excel file path, and then compares the file names in the specified Excel column against the files in the given folder. It will report which files are missing from the folder and include the reason for each case (missing in the folder or already exists in the folder):
python
import os
import pandas as pd
def find_missing_files(folder_path, excel_file_path):
try:
# Read the file names from the Excel file
df = pd.read_excel(excel_file_path)
# Ensure the 'File Name' column exists
if 'File Name' not in df.columns:
print("The specified Excel file does not contain a 'File Name' column.")
return
# Get the list of expected files from the Excel file and strip whitespace
expected_files = df['File Name'].dropna().tolist()
expected_files = [file.strip() for file in expected_files]
missing_files = []
# Check for missing files
for expected_file in expected_files:
# Check if file exists in the folder
if not any(expected_file == f for f in os.listdir(folder_path)):
missing_files.append((expected_file, "Missing in folder"))
# Report results
if missing_files:
print("The following files are missing from the folder:")
for file, reason in missing_files:
print(f"{file}: {reason}")
else:
print("All files listed in the Excel file are present in the folder.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
folder_path = r"path_to_your_folder" # Modify this path
excel_file_path = r"path_to_your_excel_file.xlsx" # Modify this path
find_missing_files(folder_path, excel_file_path)
Instructions:
Set Up: Please ensure you have Pandas installed. You can install it using pip install pandas openpyxl.
Modify the Paths: Replace path_to_your_folder and path_to_your_excel_file.xlsx with the actual paths.
Run the Script: Execute the script in your Python environment. It will read the Excel file, and check which files listed in the file are missing from the specified folder.
How It Works:
Reading the Excel File: The script loads the Excel file and checks for a column named "File Name".
Checking for Missing Files: It iterates through the list of expected file names and checks if each one exists in the specified folder.
Displaying Results: If any files are missing, it prints those file names along with the reason ("Missing in folder"). If all files are present, it confirms this with an appropriate message.
By running this script, you'll be able to easily identify which files listed in the Excel sheet are missing from your specified folder along with reasons.
# Ensure the 'File Name' column exists
if 'Filename ' not in df.columns:
print("The specified Excel file does not contain a 'Filename' column.")
return
# Get the list of expected files from the Excel file and strip whitespace
expected_files = df['Filename '].dropna().tolist()
expected_files = [file.strip() for file in expected_files]
missing_files = []
# Check for missing files
for expected_file in expected_files:
# Check if file exists in the folder
if not any(expected_file == f for f in os.listdir(folder_path)):
missing_files.append((expected_file, "Missing in folder"))
# Report results
if missing_files:
print("The following files are missing from the folder:")
for file, reason in missing_files:
print(f"{file}: {reason}")
else:
print("All files listed in the Excel file are present in the folder.")
except Exception as e:
print(f"An error occurred: {e}")
if name == "main":
folder_path = r"C:\Users\Administrator\Desktop\proxio" # Modify this path
excel_file_path = r"C:\Users\Administrator\Desktop\proxiio.xlsx" # Modify this path
code
find_missing_files(folder_path, excel_file_path) can u print the whole apth of misisng files
Certainly! To print the whole path of the missing files, you'll need to construct the full path based on the folder path you provided and the name of the missing files. Here's the modified version of your code that will include the full path of any missing files in the output:
python
import os
import pandas as pd
def find_missing_files(folder_path, excel_file_path):
try:
# Read the file names from the Excel file
df = pd.read_excel(excel_file_path)
# Ensure the 'Filename' column exists
if 'Filename ' not in df.columns:
print("The specified Excel file does not contain a 'Filename' column.")
return
# Get the list of expected files from the Excel file and strip whitespace
expected_files = df['Filename '].dropna().tolist()
expected_files = [file.strip() for file in expected_files]
missing_files = []
# Check for missing files
for expected_file in expected_files:
# Check if file exists in the folder
if not any(expected_file == f for f in os.listdir(folder_path)):
full_path = os.path.join(folder_path, expected_file) # Construct full path
missing_files.append((full_path, "Missing in folder"))
# Report results
if missing_files:
print("The following files are missing from the folder:")
for file_path, reason in missing_files:
print(f"{file_path}: {reason}")
else:
print("All files listed in the Excel file are present in the folder.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
folder_path = r"C:\Users\Administrator\Desktop\proxio" # Modify this path
excel_file_path = r"C:\Users\Administrator\Desktop\proxiio.xlsx" # Modify this path
find_missing_files(folder_path, excel_file_path)
Explanation of Changes:
Full Path Construction: The line full_path = os.path.join(folder_path, expected_file) constructs the full path for each missing file by combining the folder path with the expected file name.
Updated Output: The output now includes the full path of each missing file rather than just the file name.
Running the Script:
When you run this script, it will display the full paths of the files that are missing from the specified folder, along with a message indicating that they are "Missing in folder."
Note:
Ensure that the column name in your Excel sheet is consistent with what you have in the script ('Filename '), including any potential trailing spaces. If necessary, you can also use df.columns to check the exact names of the columns in the DataFrame.