pythonstringreverse

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.


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.