python - TypeError:强制转换为 Unicode:需要字符串或缓冲区

标签 python string typeerror

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

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

请有人帮助我。

最佳答案

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

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

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

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

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

只打开一次文件就可以了。

关于python - TypeError:强制转换为 Unicode:需要字符串或缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6680066/

相关文章:

python - 包 "within"模块

java - 有没有一种简单的方法可以替换Java中字符串中任意位置的字符(并获取新字符串)?

python - 使用 python 查找频繁的字符串模式

sql-server - SQL Server函数在列中显示词频

python-2.7 - 在Python中编写异常TypeError的代码

python - 与networkx的暴力图同构

python - numpy.all 有 where 参数用于什么目的

python - range() 函数产生错误 'TypeError: ' str' object is not callable'

javascript - Mongoose 架构构造函数无法识别

python - 你能在 Python 脚本中编译 C++ 吗?