本文介绍了将字符串参数用于不带引号的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数,意在从URL下载文件并将其写入磁盘,同时强加一个特定的文件扩展名。目前,它看起来像这样:
进口请求
进口os
def getpml(url,filename):
psc = requests.get(url)
outfile = os.path.join(os.getcwd(),filename +'。pml')
f = open( outfile,'w')
f.write(psc.content)
f.close()
try:
with open(outfile)as f:
print 文件成功写入
除了IOError作为e:
打印I / O错误,文件未写入
返回
当我尝试像
getpml('http://www.mysite。 com / data.txt','download')
我在当前工作目录download.pml中找到合适的文件。但是,当我为没有'符号的相同参数提供函数时,Python说'NameError:name'下载没有定义'(URL产生语法错误)。如果在函数本身中使用 str(filename)
或类似的东西,甚至会发生这种情况。
I宁愿不必用引号字符输入函数的参数 - 它只是使输入URL等稍微困难一些。有任何想法吗?我认为有一个简单的方法可以做到这一点,但是我的Python技能是不稳定的。
解决方案不,这是不可能的。当你输入Python源代码时,你必须在字符串周围输入引号。否则,Python无法知道字符串开始和结束的位置。
看起来您也有更常见的误解。调用 getpml(http://www.mysite.com)
不带引号不会用不带引号的相同参数调用它。根本没有任何争论。这并不是说有带引号的参数和不带引号的参数。 Python不像讲一种自然的人类语言,在那里你可以发出任何声音,而聆听者可以找出你的意思。 Python代码只能由某些构建块(对象名称,字符串,运算符等)组成,并且URL不是其中之一。
I've got a function meant to download a file from a URL and write it to a disk, along with imposing a particular file extension. At present, it looks something like this:
import requests
import os
def getpml(url,filename):
psc = requests.get(url)
outfile = os.path.join(os.getcwd(),filename+'.pml')
f = open(outfile,'w')
f.write(psc.content)
f.close()
try:
with open(outfile) as f:
print "File Successfully Written"
except IOError as e:
print "I/O Error, File Not Written"
return
When I try something like
getpml('http://www.mysite.com/data.txt','download')
I get the appropriate file sitting in the current working directory, download.pml. But when I feed the function the same arguments without the ' symbol, Python says something to the effect of "NameError: name 'download' is not defined" (the URL produces a syntax error). This even occurs if, within the function itself, I use str(filename)
or things like that.
I'd prefer not to have to input the arguments of the function in with quote characters - it just makes entering URLs and the like slightly more difficult. Any ideas? I presume there is a simple way to do this, but my Python skills are spotty.
解决方案
No, that cannot be done. When you are typing Python source code you have to type quotes around strings. Otherwise Python can't tell where the string begins and ends.
It seems like you have a more general misunderstanding too. Calling getpml(http://www.mysite.com)
without quotes isn't calling it with "the same argument without quotes". There simply isn't any argument there at all. It's not like there are "arguments with quotes" and "arguments without quotes". Python isn't like speaking a natural human language where you can make any sound and it's up to the listener to figure out what you mean. Python code can only be made up of certain building blocks (object names, strings, operators, etc.), and URLs aren't one of those.
这篇关于将字符串参数用于不带引号的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!