【问题标题】:TypeError: coercing to Unicode: need string or bufferTypeError:强制转换为 Unicode:需要字符串或缓冲区
【发布时间】:2011-10-04 12:52:24
【问题描述】:

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

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

请有人帮助我。

【问题讨论】:

    标签: python string typeerror


    【解决方案1】:

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

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

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

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

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

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

    【讨论】:

    【解决方案2】:

    您正在尝试将文件对象作为文件名传递。尝试使用

    infile = '110331_HS1A_1_rtTA.result'
    outfile = '2.txt'
    

    在代码的顶部。

    (open() 的双重使用不仅会导致尝试再次打开文件时出现问题,还意味着infileoutfile 在执行过程中永远不会关闭,尽管它们可能会程序结束后关闭。)

    【讨论】:

      【解决方案3】:

      对于不太具体的情况(不仅仅是问题中的代码 - 因为这是 Google 针对此通用错误消息的第一个结果之一。在运行某些带有 None 参数的 os 命令时也会发生此错误。

      例如:

      os.path.exists(arg)  
      os.stat(arg)
      

      当 arg 为 None 时会引发此异常。

      【讨论】:

      • 谢谢。那个python错误代码真的很误导人。
      【解决方案4】:

      这是我为 Python 2 找到的最佳方法:

      def inplace_change(file,old,new):
              fin = open(file, "rt")
              data = fin.read()
              data = data.replace(old, new)
              fin.close()
      
              fin = open(file, "wt")
              fin.write(data)
              fin.close()
      

      一个例子:

      inplace_change('/var/www/html/info.txt','youtub','youtube')
      

      【讨论】:

        猜你喜欢
        • 2011-05-13
        • 2021-03-28
        • 2015-02-01
        • 2014-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多