简体   繁体   English

Python 在文件名末尾写反斜杠

[英]Python writing backslash on end of filename

I am trying to walk a directory structure (Windows) and the UTF characters are giving me a hassle.我正在尝试遍历目录结构(Windows),而 UTF 字符给我带来了麻烦。 Specifically it is adding a backslash on the end of each filename.具体来说,它是在每个文件名的末尾添加一个反斜杠。

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)

Without the '\n' the file is one big long string without the added backslash:没有 '\n' 文件是一个没有添加反斜杠的大长字符串:

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

With it I get the following:有了它,我得到以下信息:

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

While I can deal with the extra character in the program I am going to read this into I'd rather know why this is happening.虽然我可以处理程序中的额外字符,但我将把它读入我宁愿知道为什么会发生这种情况。

That's not the way to redirect to a file and no need to micro-manage encoding.这不是重定向到文件的方式,也不需要微观管理编码。

.join() adds a backslash between every element joined, including between filename and \n . .join()在每个加入的元素之间添加一个反斜杠,包括在filename\n之间。 Let print add the newline as shown below or use .write(tmp + '\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)

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

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