类型错误:强制转换为 Unicode:需要字符串或缓冲区 [英] TypeError: coercing to Unicode: need string or buffer

查看:29
本文介绍了类型错误:强制转换为 Unicode:需要字符串或缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码返回以下错误消息:

This code returns the following error message:

  • 以 open (infile, mode='r', buffering=-1) 作为 in_f,以 open (outfile, mode='w', buffering=-1) 作为 out_f:类型错误:强制转换为 Unicode:需要字符串或缓冲区,找到文件

  • with open (infile, mode='r', buffering=-1) as in_f, open (outfile, mode='w', buffering=-1) as out_f: TypeError: coercing to Unicode: need string or buffer, file found

# 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')

请有人帮助我.

推荐答案

您正试图打开每个文件两次!首先你要做:

You're trying to open each file twice! First you do:

infile=open('110331_HS1A_1_rtTA.result','r')

然后你再次将 infile(它是一个文件对象)传递给 open 函数:

and then you pass infile (which is a file object) to the open function again:

with open (infile, mode='r', buffering=-1)

open 当然期望它的第一个参数是文件名,而不是打开的文件!

open is of course expecting its first argument to be a file name, not an opened file!

只打开一次文件,你应该没问题.

Open the file once only and you should be fine.

这篇关于类型错误:强制转换为 Unicode:需要字符串或缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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