-1

I just want to write the data from File_1.txt, File_2.txt and File_3.txt into Final.txt. Below is the code which I have written:

with open("Final.txt",'a+') as _:
    try:
        with open("File_1.txt") as f1, open("File_2.txt") as f2, open("File_3.txt") as f3:
            _.writelines([f1.read(), f2.read(), f3.read()])
            _.write('\n')
    except Exception:
        pass

Suppose if File_1.txt, File_2.txt or File_3.txt is missing, I just want to write from the remaining available files.

Example: Suppose File_1.txt is missing, remaining files data (File_2.txt and File_3.txt) should be written in Final.txt.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Kandan Siva
  • 471
  • 2
  • 9
  • 20
  • 3
    As a side note, don't use `_` as name. By convention it is used for **unused** names/variables, i.e. one that you don't care about and are throw-away. Yours is very much in use. – buran Jun 26 '22 at 13:06

4 Answers4

2

Be explicit. Separate the logic and handle every file on its own.

def read_file(filename):
    with open(filename) as f:
        return f.read()

list_of_files = ["File_1.txt", "File_2.txt", "File_3.txt"]:
files_content = []

for filename in list_of_files:
    try:
        files_content.append(read_file(filename))
    except OSError:
        continue

with open("Final.txt", 'a+') as f:
    f.writelines(files_content)
    f.write('\n')

Some people might prefer to handle the exception inside read_file but that is not the point here.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • 1
    Surprised you advocate the accumulation of data in memory rather than just writing to the output file as soon as you get the input data. Is there a reason for that? – DarkKnight Jun 26 '22 at 13:12
  • @AlbertWinestein No, not really, except for keeping the example simple and the assumption that the files do not contain GBs of data – DeepSpace Jun 26 '22 at 13:13
2

It is very simple just loop through every file and save the content from those files or directly write this inside the final text file.

You can try this.

with open("Final.txt",'a+') as final_txt:
    result_lst = []
    l = ['File_1.txt','File_2.txt','File_3.txt']
    for a in l:
        try:
            with open(a) as f:
                result_lst.append(f.read())
        except FileNotFoundError:
            pass
    final_txt.writelines(result_lst)
    final_txt.write('\n')

OR

with open("Final.txt",'a+') as final_txt:
    l = ['File_1.txt','File_2.txt','File_3.txt']
    for a in l:
        try:
            with open(a) as f:
                final_txt.write(f.read())
        except FileNotFoundError:
            pass
    final_txt.write('\n')

Both Code Gives Same Output.

You don't need to worry about the closing the file if there is any error the file guaranteed close because of the with statement

The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler.

Information from this post

codester_09
  • 5,622
  • 2
  • 5
  • 27
0

When you open all files in a single with statement like that, one missing file will invoke the except and nothing will be written to the final file. Just iterate over the input files and try to read them one at a time:

with open("Final.txt", 'w') as out_file:
    input_files = ["File_1.txt", "File_2.txt", "File_3.txt"]
    for input_file in input_files:
        try:
            with open(input_file) as f:
                out_file.write(f.read())
                out_file.write('\n')
        except FileNotFoundError:
            continue
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
-1

Just have a loop which writes the contents if the file is present.

def writeIfExists(filename, dest):
    try:
        with open(filename) as f:
            dest.writelines([f.read()])
    except FileNotFoundError:
        pass

with open("Final.txt",'a+') as _:
    try:
        for filename in ["File_1.txt", "File_2.txt", "File_3.txt"]:
            writeIfExists(filename, _)
        _.write('\n')
    except Exception:
        pass
quamrana
  • 37,849
  • 12
  • 53
  • 71