Python TypeError:强制使用Unicode:需要字符串或缓冲区
此代码返回以下错误消息:Python TypeError:强制使用Unicode:需要字符串或缓冲区,python,string,typeerror,Python,String,Typeerror,此代码返回以下错误消息: 将open(infle,mode='r',buffering=-1)作为in\u f,open(outfile,mode='w',buffering=-1)作为out\u f: TypeError:强制使用Unicode:需要字符串或缓冲区,找到文件 # Opens each file to read/modify infile=open('110331_HS1A_1_rtTA.result','r') outfile=open('2.txt','w') impor
- 将open(infle,mode='r',buffering=-1)作为in\u f,open(outfile,mode='w',buffering=-1)作为out\u 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')
然后将infle
(文件对象)再次传递到open
函数:
with open (infile, mode='r', buffering=-1)
open
当然希望它的第一个参数是文件名,而不是打开的文件
只打开一次文件,就可以了。您试图将文件对象作为文件名传递。试用
infile = '110331_HS1A_1_rtTA.result'
outfile = '2.txt'
在代码的顶部
(重复使用
open()
不仅会导致再次尝试打开文件时出现问题,还意味着infle
和outfile
在执行过程中永远不会关闭,尽管它们可能会在程序结束后关闭。)对于不太具体的情况(不仅仅是问题中的代码——因为这是Google中第一个针对此通用错误消息的结果之一。当运行某个os命令时,如果没有参数,也会发生此错误
例如:
os.path.exists(arg)
os.stat(arg)
将在arg为None时引发此异常。以下是我为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')
谢谢。那个python错误代码真的有误导性。你能看看我的帖子,看看我做错了什么吗?