Home > OS >  How to write data to a file after the last line?
How to write data to a file after the last line?

Time:10-01

Below I have a snippet which is writing some data into a file. Please note that the input of the lists xml_files and txt_files could change every now and then, this is just some reproduceable test data

xml_files = ['text0.xml', 'text1.xml', 'text2.xml', 'text3.xml']
txt_files = ['text0.txt', 'text1.txt']

    today  = datetime.date.today().strftime('%Y-%m-%d')
    with open(log_location   '/'   today   '-logT2M_II.txt', 'a') as output:
        if output.tell() == 0: 
            output.write('Processed XML files: ')
        output.write('\t'   xml_files   '\n')
        if output.tell():
            output.write('Processed TXT files: ')
        output.write('\t'   xml_files   '\n')

I want my file to look like below so I actually want Processed TXT files to be written after the last xml file. Right now I have 4 XML files but this changes continuously, it could be 3 could be 7 could be 12. The same applies for TXT files, the amount of TXT files could also change.

Processed XML files:
      text0.xml
      text1.xml
      text2.xml
      text3.xml
Processed TXT files:
      text0.txt
      text1.txt

My current output:

TypeError: can only concatenate list (not "str") to list
    

CodePudding user response:

The problem is when you do

'/t'   xml_files # str()   list()

Which doesn't make sense. You need to loop over the elements in the list, and add them one by one.

Try this:

output.write('Processed XML files: \n')
for xml_file in  xml_files:
    output.write('\t'   xml_file   '\n')

output.write('Processed TXT files: \n')
for txt_file in  txt_files:
    output.write('\t'   txt_file   '\n')

  • Related