导入文本文件会导致错误 [英] Importing a text file gives error

查看:183
本文介绍了导入文本文件会导致错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中包含以下数据:

  5298 10036 4 360 8 
6128 11947 2 385 7
9472 18930 0 233 4
5056 9790 1 293 6

I使用下面的代码读取这个文件:

  file1 = open(test.txt,r)
lines = file1.readlines()
BF = [map(float,line.split())for line in line]

这给了我以下错误:

 不能将字符串转换为float:$ 5 

为什么我会看到这个错误?

更新:

 打印行

显示:

  ['\xff\xfe5\x002\x009\x008\ x00\t\x001\x000\x000\x003\x006\x00\t\x004\x00\t\x003\x006\x000\x00\t\\ \\x008\x00\r\x00\\\
','\x006\x001\x002\x008\x00\t\x001\x001\x009\x004\x007\x00\t\x002\x00\ t\x003\x008\x005\x00\t\x007\x00\r\x00\\\
','\x009\x004\x007\x002\x00\\ \\t\x001\x008\x009\x003\x000\x00\t\x000\x00\t\x002\x003\x003\x00\t\x004 \x00\r\x00\\\
','\x005\x000\x005\x006\x00\t\x009\x007\x009\x000\x00\ t\x001\x00\t\x002\x009\x003\x00\t\x006\x00\r\x00\\\
','\x001\x005\\ \\x000\x006\x004\x00\t\x003\x000\x001\x006\x000\x00\t\x001\x00\t\x003\x001 \x002\x00\t\x008\x00']


utf-16

> BOM,这是 0xFE 0xFF 这被解释为ÿþ

  file1 = open(test.txt,r ,encoding =utf-16)

当你使用python 2时, p>

  import io 
file1 = io.open(test.txt,r,encoding =utf-16 )


I have a text file that has the following data:

5298    10036   4   360 8
6128    11947   2   385 7
9472    18930   0   233 4
5056    9790    1   293 6

I read this file using the following code:

file1 = open("test.txt","r")
lines = file1.readlines()       
BF=[map(float, line.split()) for line in lines]

This gives me the following error:

could not convert string to float: ÿþ5

Why do I see this error?

Update:

print lines 

shows:

['\xff\xfe5\x002\x009\x008\x00\t\x001\x000\x000\x003\x006\x00\t\x004\x00\t\x003\x006\x000\x00\t\x008\x00\r\x00\n', '\x006\x001\x002\x008\x00\t\x001\x001\x009\x004\x007\x00\t\x002\x00\t\x003\x008\x005\x00\t\x007\x00\r\x00\n', '\x009\x004\x007\x002\x00\t\x001\x008\x009\x003\x000\x00\t\x000\x00\t\x002\x003\x003\x00\t\x004\x00\r\x00\n', '\x005\x000\x005\x006\x00\t\x009\x007\x009\x000\x00\t\x001\x00\t\x002\x009\x003\x00\t\x006\x00\r\x00\n', '\x001\x005\x000\x006\x004\x00\t\x003\x000\x001\x006\x000\x00\t\x001\x00\t\x003\x001\x002\x00\t\x008\x00']

解决方案

You have a utf-16 BOM, this is 0xFE 0xFF which is interpreted as ÿþ, you need to open the file and pass the encoding.

file1 = open("test.txt","r", encoding = "utf-16")

As you using python 2 you could try this:

import io
file1 = io.open("test.txt","r", encoding = "utf-16")

这篇关于导入文本文件会导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆