如何从文件名中删除BOM字符?

时间:2018-05-11 16:30:15

标签: python python-3.x

我正在尝试打开特定文件,但收到了:

FileNotFoundError: No such file: C:\\Users\\Jonis\\Desktop\\New folder\\vardai tikri\\becach_besmile_vardai_failas_\ufeff3.txt

我发现这是文件名末尾的BOM字符,显示为/ufeff3。这就是我试过的:

  1. encoding = 'utf-8-sig'无效
  2. 尝试修改文件的名称:filename[:-11]+"3.txt",但没有任何运气
  3. 代码:

    filename = "C:\\Users\\Jonis\\Desktop\\New folder\\vardai tikri\\becach_besmile_vardai_failas_3.txt"
    with open(filename, mode="r", encoding="utf-8") as file:
        for line in file:
            print(line)
    

    如何从文件名中删除BOM扩展名?

1 个答案:

答案 0 :(得分:0)

看了一段时间后,我发现了一个有效的解决方案。 我只需将“\ ufeff”替换为空字符串“”

filename = "C:\\Users\\Jonis\\Desktop\\New folder\\vardai tikri\\becach_besmile_vardai_failas_3.txt"

filename = filename.replace("\ufeff", "")
with open(filename, mode="r", encoding="utf-8") as file:
    for line in file:
        print(line)