Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中的Base64字符串格式_Python_Base64_String Formatting - Fatal编程技术网

python中的Base64字符串格式

python中的Base64字符串格式,python,base64,string-formatting,Python,Base64,String Formatting,在python 2.7中,如何正确地将base64数据输入到字符串格式中,我遇到了一个问题。以下是相关的代码片段: fileExec = open(fileLocation, 'w+') fileExec.write(base64.b64decode('%s')) %(encodedFile) # encodedFile is base64 data of a file grabbed earlier in the script. fileExec.close() os.startfile(fi

在python 2.7中,如何正确地将base64数据输入到字符串格式中,我遇到了一个问题。以下是相关的代码片段:

fileExec = open(fileLocation, 'w+')
fileExec.write(base64.b64decode('%s')) %(encodedFile) # encodedFile is base64 data of a file grabbed earlier in the script.
fileExec.close()
os.startfile(fileLocation)
尽管看起来很愚蠢,但由于脚本实际执行的操作,我需要在本例中使用字符串格式,但当我启动脚本时,我收到以下错误:

TypeError: Incorrect Padding
我不太确定需要对“%s”执行什么操作才能使其正常工作。有什么建议吗?我是否使用了错误的字符串格式

更新:这里有一个关于我最终要实现的目标的更好的想法:

encodedFile = randomString() # generates a random string for the variable name to be written 
fileExec = randomString()
... snip ...
writtenScript += "\t%s.write(base64.b64decode(%s))\n" %(fileExec, encodedFile) # where writtenScript is the contents of the .py file that we are dynamically generating

我必须使用字符串格式,因为变量名在我们制作的python文件中并不总是相同的。

该错误通常意味着base64字符串可能没有正确编码。但在这里,这只是代码中逻辑错误的副作用。 你所做的基本上是这样的:

a = base64.b64decode('%s')
b = fileExec.write(a)
c = b % (encodedFile)
因此,您正在尝试解码文本字符串“%s”,但失败

它应该更像这样:

fileExec.write(base64.b64decode(encodedFile))
[编辑:使用冗余字符串格式…请不要在实际代码中这样做]

fileExec.write(base64.b64decode("%s" % encodedFile))

更新后的问题显示B64解码部分在字符串中,而不是在代码中。这是一个显著的区别。字符串中的代码还缺少一组围绕第二种格式的内部引号:

writtenScript += "\t%s.write(base64.b64decode('%s'))\n" % (fileExec, encodedFile)

(注意单引号…

您根本不需要使用字符串格式:
b64decode(encodedFile)
此外,似乎您应该在
fileExec.write(base64.b64decode('%s'))%(encodedFile)
行上得到一个错误,因为文件
write()
方法返回
None
,这将导致
类型错误:%
异常的操作数类型不受支持。虽然通常我不会使用字符串格式,在这种情况下,我需要这样做,因为此脚本正在写入另一个脚本,实际的“encodedFile”变量名将随机生成。不幸的是,在这种情况下,我需要使用字符串格式。将其写入base64.b64解码(encodedFile)不是一个选项。有没有一种方法可以通过某种格式调用“encodedFile”呢?为什么是“必需的”?在这种情况下这样做没有任何意义,完全是多余的。也就是说,您需要更改操作顺序,上面我向您展示了您当前的顺序(您正在尝试格式化File.write的返回值,它始终是非btw)@Ondaje您对代码中正在发生的机制非常困惑。你需要退后一步,详细说明你想要完成的事情,因为这和你刚开始做的事情完全不一样。你编辑的内容正是我想要的。非常感谢。更新后的问题显示B64解码部分在字符串中,而不是在代码中。这是一个显著的区别。