Python 在文件名末尾写反斜杠

Python writing backslash on end of filename

我正在尝试遍历目录结构 (Windows),但 UTF 字符给我带来了麻烦。具体来说,它是在每个文件名的末尾添加一个反斜杠。

import os, sys
f = open('output.txt','wb')
sys.stdout = f
tmp=''.encode('utf-8')
for dirname, dirnames, filenames in os.walk('d:\media'):
    # print path to all filenames.
    for filename in filenames:
        tmp=os.path.join(dirname, filename,'\n').encode('utf-8')
        sys.stdout.write(tmp)

没有 '\n' 文件是一个没有添加反斜杠的大长字符串:

d:\media\dir.txtd:\media\Audio\Acda en de Munnik - Waltzing Mathilda (live).mp3d:\media\Audio\BalladOfMosquito.mp3\

有了它,我得到了以下信息:

d:\media\dir.txt\
d:\media\Audio\Acda en de Munnik - Waltzing Mathilda (live).mp3\
d:\media\Audio\BalladOfMosquito.mp3\

虽然我可以处理程序中的额外字符,但我将阅读它,我更想知道为什么会这样。

这不是重定向到文件的方式,也不需要对编码进行微观管理。

.join() 在每个连接的元素之间添加反斜杠,包括 filename\n 之间。让 print 添加换行符,如下所示或使用 .write(tmp + '\n').

import os, sys

# Open the file in the encoding you want.
# Use 'with' to automatically close the file.
with open('output.txt','w',encoding='utf8') as f:

    # Use a raw string r'' if you use backslashes in paths to prevent accidental escape codes.
    for dirname, dirnames, filenames in os.walk(r'd:\media'):
        for filename in filenames:
            tmp = os.path.join(dirname, filename)

            # print normally adds a newline, so just redirect to a file
            print(tmp,file=f)