python-预期的str,字节或os.PathLike对象,而不是InMemoryUploadedFile
作者:互联网
我有一种读取Newick文件并在Django框架中返回以下字符串的方法:
def handle_uploaded_file(f):
output = " "
for chunk in f.chunks():
output += chunk.decode('ascii')
return output.replace("\n", "").replace("\r", "")
def post(self, request):
form = HomeForm(request.POST, request.FILES)
if form.is_valid():
input = handle_uploaded_file(request.FILES['file'])
treeGelezen = Tree(input, format=1)
script, div = mainmain(treeGelezen)
form = HomeForm()
args = {'form': form, 'script': script, 'div': div}
return render(request, self.template_name, args)
对于普通的Newick文件,它的工作正常,但我也有一些文件,在文件的开头有一个字符串.我正在尝试使用另一种方法来检查文件之前是否具有以下字符串(某些文件就是这种情况):“ newick;”并删除该字符串(如果找到).它在本地工作,但我似乎无法合并它们.这是本地的样子:
def removeNewick(tree_with_newick):
for x in tree_with_newick:
if x.startswith('newick;'):
print('')
return x
filepath = "C:\\Users\\msi00\\Desktop\\ncbi-taxanomy.tre"
tree_with_newick = open(filepath)
tree = Tree(newick=removeNewick(tree_with_newick), format=1)
当我仅在python中指定路径时,它完美地工作,所以我尝试在Django中将它们组合如下:
def handle_uploaded_file(f):
tree_with_newick = open(f)
for x in tree_with_newick:
if x.startswith('newick;'):
print('')
return cutFile(x)
def cutFile(f):
output = " "
for chunk in f.chunks():
output += chunk.decode('ascii')
return output.replace("\n", "").replace("\r", "")
def post(self, request):
form = HomeForm(request.POST, request.FILES)
if form.is_valid():
input = handle_uploaded_file(request.FILES['file'])
treeGelezen = Tree(input, format=1)
script, div = mainmain(treeGelezen)
form = HomeForm()
args = {'form': form, 'script': script, 'div': div}
return render(request, self.template_name, args)
这不起作用,并且会出现以下错误:
expected str, bytes or os.PathLike object, not InMemoryUploadedFile
我已经进行了两天的工作,无法弄清为什么会弹出错误.
解决方法:
因为函数handle_uploaded_file(f)试图打开一个已经打开的文件,所以发生了错误.
request.FILES [‘file’]的值是InMemoryUploadedFile,可以像普通文件一样使用.您无需再次打开它.
要解决此问题,只需删除尝试打开文件的行:
def handle_uploaded_file(f):
for x in f:
if x.startswith('newick;'):
print('')
return cutFile(x)
标签:ncbi,python,django,ete3 来源: https://codeday.me/bug/20191109/2010649.html