Python 迭代文件时文件名不正确
我想在文件夹中所有文件的每一行末尾添加一个字符,因此我编写了一些代码,以便遍历每个文件并添加所需的更改,但是输出文件的文件名与原始文件不同,下面是我编写的代码Python 迭代文件时文件名不正确,python,Python,我想在文件夹中所有文件的每一行末尾添加一个字符,因此我编写了一些代码,以便遍历每个文件并添加所需的更改,但是输出文件的文件名与原始文件不同,下面是我编写的代码 import os output = '/home/test/Playground/Python/filemodification/output/' def modification(): with open(files, 'r') as istr: with open(str(output) + st
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'>
我知道这个问题可能与此有关
with open(str(output) + str(files), 'w') as ostr:
但我还没有找到一种不同的方法来完成这项任务
如果有人能给我指出正确的方向或提供一个代码示例来完成这项任务,我将不胜感激
谢谢返回对象。您可以通过访问其.name
属性或通过.path
访问其完整路径来获取其文件名
例如:
您可能需要使用
listdir()
方法
with open(str(output) + str(files), 'w') as ostr:
for entry in os.scandir(directory):
print(entry.path)