Python - read text file with weird utf-16 format

前端 未结 4 819
走了就别回头了
走了就别回头了 2021-01-17 17:00

I\'m trying to read a text file into python, but it seems to use some very strange encoding. I try the usual:

file = open(\'data.txt\',\'r\')

lines = file.         


        
4条回答
  •  长发绾君心
    2021-01-17 17:41

    This piece of code will do the necessary

    file_handle=open(file_name,'rb')
    file_first_line=file_handle.readline()
    file_handle.close()
    print file_first_line
    if '\x00' in file_first_line:
        file_first_line=file_first_line.replace('\x00','')
        print file_first_line
    

    When you try to use 'file_first_line.split()' before replacing, the output would contain '\x00' i just tried replacing '\x00' with empty and it worked.

提交回复
热议问题