Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/15.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 使用urllib2为从URL读取的文本使用configparser_Python_Configparser - Fatal编程技术网

Python 使用urllib2为从URL读取的文本使用configparser

Python 使用urllib2为从URL读取的文本使用configparser,python,configparser,Python,Configparser,我必须从浏览器中读取txt ini文件。[这是必需的] res = urllib2.urlopen(URL) inifile = res.read() 然后我想基本上用和读取任何txt文件相同的方法来使用它 config = ConfigParser.SafeConfigParser() config.read( inifile ) 但是现在看起来我不能使用它,因为这实际上是一个字符串 有人能提出一个解决办法吗?你想要的--想必,你甚至可以逃脱: res = urllib2.urlopen(

我必须从浏览器中读取txt ini文件。[这是必需的]

res = urllib2.urlopen(URL)
inifile = res.read()
然后我想基本上用和读取任何txt文件相同的方法来使用它

config = ConfigParser.SafeConfigParser()
config.read( inifile )
但是现在看起来我不能使用它,因为这实际上是一个字符串

有人能提出一个解决办法吗?

你想要的--想必,你甚至可以逃脱:

res = urllib2.urlopen(URL)
config = ConfgiParser.SafeConfigParser()
config.readfp(res)
假设
urllib2.urlopen
返回一个足够像文件的对象(即它有一个
readline
方法)。为便于调试,您可以执行以下操作:

config.readfp(res, URL)
如果必须从字符串中读取数据,可以将整个内容打包到
io.StringIO
(或
StringIO.StringIO
)缓冲区中,然后从中读取:

import io

res = urllib2.urlopen(URL)
inifile_text = res.read()

inifile = io.StringIO(inifile_text)
inifile.seek(0)
config.readfp(inifile)