迭代文件时文件名不正确

2024-04-27 03:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在文件夹中所有文件的每一行末尾添加一个字符,因此我编写了一些代码,以便遍历每个文件并添加所需的更改,但是输出文件的文件名与原始文件不同,下面是我编写的代码

import os
output = '/home/test/Playground/Python/filemodification/output/'
def modification():
       with open(files, 'r') as istr:
           with open(str(output) + str(files), 'w') as ostr:
               for line in istr:
                   line = line.rstrip('\n') + 'S'
                   print(line, file=ostr)

directory = '/home/test/Playground/Python/filemodification/input'
for files in os.scandir(directory):
       #print(files.path)
       print(files)
       #print(output)
       #print(type(files))
       modification()

一旦我运行代码,我就会得到以下文件名

<DirEntry 'input.txt'>

这是原始文件名

input.txt

我知道这个问题可能与此有关

with open(str(output) + str(files), 'w') as ostr:

但我还没有找到一种不同的方法来完成这项任务

如果有人能给我指出正确的方向或提供一个代码示例来完成这项任务,我将不胜感激

谢谢


Tags: 文件代码homeinputoutputos文件名as