繁体   English   中英

遍历文件时文件名不正确

[英]Incorrect filename when iterating through files

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

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:

但我还没有找到以不同方式执行此任务的方法

如果有人可以指出我正确的方向或提供可以完成此任务的代码示例,将不胜感激

谢谢

os.scandir返回os.DirEntry对象。 您可以通过访问它们的.name属性或通过.path访问它们的完整路径来获取它们的文件名。

例如:

for entry in os.scandir(directory):
    print(entry.path)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM