0

I am trying to append the data from one file (OLD) to another file (NEW) in folder for the multiple files for the matching same filename. Its working fine when only number files are matching, when there is missing file in the NEW folder it will stop and with an error :

FileNotFoundError: [Errno 2] No such file or directory

But if there is a missing file in OLD folder there will be no error

How to fix this? Normally OLD folder will have more files than the new folder.

Another issue I am facing is this code works only for csv files not for the xls files and I am getting the error

UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 1778: character maps to <undefined>

My old files are in .xls Format, I want to retain it in xls format only

Working Code only for same number of files and CSV

import os

existing_files_directory = "C:/Misc/Quali Test/Phase 2/OLD"
new_files_directory = "C:/Misc/Quali Test/Phase 2/NEW"


existing_file_names = os.listdir(existing_files_directory)


for file_name in existing_file_names:
    existing_file_path = os.path.join(existing_files_directory, file_name)
    new_file_path = os.path.join(new_files_directory, file_name)

    with open(existing_file_path, "a") as existing_file:
 
        
        with open(new_file_path, "r") as new_file:
         

            new_file_contents = new_file.read()

            existing_file.write(new_file_contents)

                      
    existing_file.close()
    new_file.close()

Need help on

  1. if the NEW folder is less in number it should skip and append for only available files.
  2. Looking for xls files
Hoodlum
  • 950
  • 2
  • 13
Yogs
  • 13
  • 2
  • You really should ask only one question at a time. More makes it difficult to answer concisely. For the question about XLS format files: I doubt you can just append the raw xls files, you probably need to use a proper XLS parsing library to read and write it. You might want to have a look [here](https://stackoverflow.com/questions/2942889/reading-parsing-excel-xls-files-with-python) – Hoodlum Aug 11 '23 at 21:09
  • 1
    also, your example code does the opposite of what you describe. it reads from NEW and appends to OLD. this is probably part of the reason why you're getting the `FileNotFoundError`. – Hoodlum Aug 11 '23 at 21:16
  • Thanks a lot for "Read XLS" – Yogs Aug 12 '23 at 19:45
  • For the second request, I wanted to Append the New data to the old File, Old file will have more information. I tried to revere it but getting error – Yogs Aug 13 '23 at 15:36
  • I'm very confused. this is not what you described in your question. but in this case maybe you should only read and append what's in the NEW folder (i.e. `for file_name in os.listdir(new_files_directory):` etc...) – Hoodlum Aug 13 '23 at 18:28

0 Answers0