Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reverse all text files in all path with output separate independently

My code run successfully but I want that output files will be separate independently.

import os

path = '/txt_files_path/' # txt files path

for filename in filter(lambda p: p.endswith("txt"), os.listdir(path)):
    filepath = os.path.join(path, filename)
    with open(filepath, mode='r') as f:
      for line in f:
        addr = line.rstrip()

    var = line.rstrip()
    data = var
    data_1 = data[::-1]

    os.system(f'echo {(var[::-1])} >> output.txt') # single txt reverse files output write

The problem is the last line.

I want that output files will be separate independently.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

import os

path = 'test_folder/' # txt files path

for filename in filter(lambda p: p.endswith("txt"), os.listdir(path)):
    filepath = os.path.join(path, filename)
    with open(filepath, mode='r') as f:
      for line in f:
        addr = line.rstrip()

    var = line.rstrip()
    data = var
    data_1 = data[::-1]

    os.system(f'echo {(var[::-1])} >> {filename}_reversed.txt') # single txt reverse files output write

Your code repeatedly writes (and hence overwrites) to the same file. All you need to do is everytime it writes, make sure you are writing to a unique file.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading