将结果保存在与输入文件同名的文件中

Save results in the files with same name as input files

我正在编写如下 python 代码:

import os
count = 0
for doc in os.listdir('/home/krupa/Krupa/Mirellas_Image_Annotation_Data/Test/Html_Files/Texts'):
   if doc.endswith(".txt"):
      with open(doc, 'r') as f:
          single_line = ''.join([line for line in f])
          single_space = ' '.join(single_line.split())

      with open(doc.format(count) , "w") as doc:
        doc.write(single_space)
    count += 1
else:
    continue

在这里,我想以相同的文件名但使用不同的扩展名(比如 .key)写入输出。我该怎么做?请帮忙。提前致谢

import os
count = 0
for doc in os.listdir('/home/krupa/Krupa/Mirellas_Image_Annotation_Data/Test/Html_Files/Texts'):
    doc1 = "doc_path" + doc
    doc2 = "new_path_where_new_file_with_new_ext_needs_to_be_saved" + doc1
    if doc1.endswith(".txt"):
    with open(doc, 'r') as f:
           single_line = ''.join([line for line in f])
           single_space = ' '.join(single_line.split())

           with open(doc2.format(count) , "w") as doc2:
               doc2.write(single_space)
           count += 1
else:
continue