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)
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 some files are not copied to the destinaiton folder so for those in the excel rpovided add one column missing ..and if it is not copied by any resaon add not dfound for that row and rest will have found
To modify your existing code so that it adds a column to the Excel file indicating whether files were "found" or "not found" based on your copying logic, you can follow these steps:
Create a DataFrame to store the results of the file copy operation.
For each file name read from the Excel, check if the file was copied successfully.
Update the DataFrame to mark each file as 'found' or 'not found'.
Write the updated DataFrame back to a new Excel file.
Here’s how you can implement those changes in your code:
python
import os
import shutil
import pandas as pd
import zipfile
def copy_files(source_folder, destination_folder, file_names, found_status):
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}'!")
found_status[filename] = 'found'
else:
print(f"File '{filename}' already exists in the destination folder.")
found_status[filename] = 'found'
elif filename.endswith('.zip'):
zip_path = os.path.join(dirpath, filename)
extract_and_copy_files(zip_path, destination_folder, file_names, found_status)
def extract_and_copy_files(zip_path, destination_folder, file_names, found_status):
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}'!")
found_status[filename] = 'found'
else:
print(f"File '{filename}' already exists in the destination folder.")
found_status[filename] = 'found'
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 []
def update_excel_file(file_names, found_status, output_excel_path):
"""Update the Excel file with found statuses."""
results = {
'File Name': [],
'Status': []
}
for file_name in file_names:
results['File Name'].append(file_name)
if file_name in found_status:
results['Status'].append(found_status[file_name])
else:
results['Status'].append('not found')
df_results = pd.DataFrame(results)
df_results.to_excel(output_excel_path, index=False)
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)
found_status = {}
if file_names:
copy_files(source_folder, destination_folder, file_names, found_status)
# Define output Excel path
output_excel_path = r"D:\GILSILISSUE1\201ISSUE1_updated.xlsx"
# Update the Excel file with found status
update_excel_file(file_names, found_status, output_excel_path)
else:
print("No file names found in the Excel file.")
Explanation of Changes:
found_status: A dictionary is initialized to keep track of whether each file was found (copied) or not.
File Copying Logic: The updated copy_files and extract_and_copy_files functions will now update the found_status dictionary.
update_excel_file Function: This function creates a new Excel file with the status of each file (found/not found).
Output Excel Path: The program saves the new Excel file with the status.
Run this modified script, and it will create a new Excel file that details the status of each file from the original list based on whether the files were found and copied successfully or not.
import os
import shutil
import pandas as pd
import zipfile
def copy_files(source_folder, destination_folder, file_names, found_status):
file_names = [name.strip() for name in file_names]
if not os.path.exists(source_folder):
print("Source folder not found!")
return
code
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}'!")
found_status[filename] = 'found'
else:
print(f"File '{filename}' already exists in the destination folder.")
found_status[filename] = 'found'
elif filename.endswith('.zip'):
zip_path = os.path.join(dirpath, filename)
extract_and_copy_files(zip_path, destination_folder, file_names, found_status)
def extract_and_copy_files(zip_path, destination_folder, file_names, found_status):
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}'")
code
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}'!")
found_status[filename] = 'found'
else:
print(f"File '{filename}' already exists in the destination folder.")
found_status[filename] = 'found'
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 update_excel_file(file_names, found_status, output_excel_path):
# UPADTE THE EXCEL WITH STATUS
results = {
'File Name': [],
'Status': []
}
code
for file_name in file_names:
results['File Name'].append(file_name)
if file_name in found_status:
results['Status'].append(found_status[file_name])
else:
results['Status'].append('not found')
df_results = pd.DataFrame(results)
df_results.to_excel(output_excel_path, index=False)
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"
code
file_names = read_file_names_from_excel(excel_file_path)
found_status = {}
if file_names:
copy_files(source_folder, destination_folder, file_names, found_status)
# UPDATED EXCEL
output_excel_path = r"D:\GILSILISSUE1\201ISSUE1_updated.xlsx"
update_excel_file(file_names, found_status, output_excel_path)
else:
print("No file names found in the Excel file.") in this my input file has so may column other than filenames i wanted all of them in the upadted execl
If you want to keep all the columns from the original Excel file in the updated file while adding the status information, you'll need to modify the update_excel_file function to merge the status information with the existing data.
Here's how to do it:
Read the entire original DataFrame, not just the 'File Name' column.
Merge the new status column with the original DataFrame.
Write the merged DataFrame back to Excel.
Here’s the modified Python code that achieves your requirements:
python
import os
import shutil
import pandas as pd
import zipfile
def copy_files(source_folder, destination_folder, file_names, found_status):
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}'!")
found_status[filename] = 'found'
else:
print(f"File '{filename}' already exists in the destination folder.")
found_status[filename] = 'found'
elif filename.endswith('.zip'):
zip_path = os.path.join(dirpath, filename)
extract_and_copy_files(zip_path, destination_folder, file_names, found_status)
def extract_and_copy_files(zip_path, destination_folder, file_names, found_status):
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}'!")
found_status[filename] = 'found'
else:
print(f"File '{filename}' already exists in the destination folder.")
found_status[filename] = 'found'
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):
try:
df = pd.read_excel(excel_file_path)
# Keep all columns and return the DataFrame
return df
except Exception as e:
print(f"Error reading Excel file: {e}")
return pd.DataFrame()
def update_excel_file(original_df, found_status, output_excel_path):
# Create a new column for status
original_df['Status'] = 'not found' # Set default status to 'not found'
# Update status for found files
for filename in found_status.keys():
if filename in original_df['File Name'].values:
original_df.loc[original_df['File Name'] == filename, 'Status'] = found_status[filename]
original_df.to_excel(output_excel_path, index=False)
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"
# Read the entire original DataFrame from the Excel file
original_df = read_file_names_from_excel(excel_file_path)
found_status = {}
if not original_df.empty:
file_names = original_df['File Name'].dropna().tolist() # Extracting the list of filenames
copy_files(source_folder, destination_folder, file_names, found_status)
# UPDATED EXCEL
output_excel_path = r"D:\GILSILISSUE1\201ISSUE1_updated.xlsx"
update_excel_file(original_df, found_status, output_excel_path)
else:
print("No file names found in the Excel file.")
Key Changes:
read_file_names_from_excel: Now returns the entire DataFrame instead of just the list of file names.
update_excel_file: Accepts the entire original DataFrame. Adds a Status column initialized to 'not found', then updates it based on the results stored in found_status.
File Name Extraction: The file names are extracted from the DataFrame inside the main function instead of a new list.
With these changes, the resulting Excel file will contain all original columns along with the Status column indicating whether each file was found or not.