反转所有路径中的所有文本文件,独立输出单独

问题描述 投票:0回答:1

我的代码运行成功,但我希望输出文件独立分开。

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

问题出在最后一行。

我希望输出文件独立分开。

python string reverse
1个回答
0
投票
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

您的代码重复写入(并因此覆盖)同一个文件。您需要做的就是每次写入时,确保写入的是唯一的文件。

© www.soinside.com 2019 - 2024. All rights reserved.