类型错误:需要字符串或缓冲区以转换为Unicode
这段代码返回了以下错误信息:
在打开文件时,出现了这个错误:
with open (infile, mode='r', buffering=-1) as in_f, open (outfile, mode='w', buffering=-1) as out_f:
TypeError: 强制转换为Unicode时出错:需要字符串或缓冲区,但找到了文件# Opens each file to read/modify infile=open('110331_HS1A_1_rtTA.result','r') outfile=open('2.txt','w') import re with open (infile, mode='r', buffering=-1) as in_f, open (outfile, mode='w', buffering=-1) as out_f: f = (i for i in in_f if i.rstrip()) for line in f: _, k = line.split('\t',1) x = re.findall(r'^1..100\t([+-])chr(\d+):(\d+)\.\.(\d+).+$',k) if not x: continue out_f.write(' '.join(x[0]) + '\n')
请有人帮帮我。
4 个回答
8
你正在尝试把文件对象当作文件名来使用。可以试试在代码的开头加上
infile = '110331_HS1A_1_rtTA.result'
outfile = '2.txt'
这行代码。
(不仅是因为重复使用open()
导致了你再次尝试打开文件的问题,还因为在程序运行过程中,infile
和outfile
这两个文件对象从来没有被关闭,虽然程序结束时它们可能会被关闭。)
10
对于这个不太具体的情况(不仅仅是问题中的代码 - 因为这是谷歌上关于这个通用错误信息的前几条结果之一)。这个错误也会在运行某些操作系统命令时出现,当参数是None的时候。
举个例子:
os.path.exists(arg)
os.stat(arg)
当参数是None时,会引发这个异常。
69
你正在尝试打开每个文件两次!首先你做了:
infile=open('110331_HS1A_1_rtTA.result','r')
然后你又把 infile
(这是一个文件对象)传给 open
函数:
with open (infile, mode='r', buffering=-1)
其实,open
函数是希望它的第一个参数是文件名,而不是已经打开的文件!
只需要打开一次文件就可以了,这样就没问题了。