【问题标题】:Python writing backslash on end of filenamePython在文件名末尾写反斜杠
【发布时间】:2020-05-20 15:50:22
【问题描述】:

我正在尝试遍历目录结构 (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\

虽然我可以处理程序中的额外字符,但我将阅读此内容,但我更想知道为什么会发生这种情况。

【问题讨论】:

    标签: python string utf-8 filenames


    【解决方案1】:

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

    .join() 在每个加入的元素之间添加一个反斜杠,包括在filename\n 之间。让打印添加如下所示的换行符或使用.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)
    

    【讨论】:

      猜你喜欢
      • 2014-09-12
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多