我是新来的Python和正在运行到读。广州文件的内容问题:阅读内容与Python
我已经有了一个完整的,我已经加上.gz文件的文件夹使用私有API以编程方式提取。每个.gz文件的内容都是一个.xml文件,所以我需要遍历该目录并提取它们。
问题是,当我以编程方式将这些.gz文件解压缩到它们各自的.xml版本时......文件创建时没有错误,当我打开一个(使用TextWrangler)时,它看起来像一个普通的.xml文件,我用十六进制编辑器查看它。另外,当我以编程方式打开.xml文件并打印它的内容时,它显示为一堆(二进制?)混乱的文本。
考虑到上述情况,如果我手动提取其中一个文件(即:使用OSX,但不是Python),该文件可以在我希望的十六进制编辑器中查看。
这里是我的代码片段(适当的进口没有显示,但它们是水珠和gzip):
searchpattern = siteid + "_" + resource + "_*.gz"
for infile in glob.glob(workingDir + searchpattern):
print infile
#read the zipped contents (https://docs.python.org/2/library/gzip.html)
f = gzip.open(infile, 'rb')
file_content = f.read()
file_content = str(file_content) #This was an attempt to fix
print file_content # This shows a bunch of mumbo jumbo
#write the contents we just read to a new file (uncompressed)
newfilename = infile[0:-3] # the filename without the ".gz"
newfilename = newfilename + ".xml"
fnew = open(newfilename, 'w+b')
fnew.write(str(file_content))
fnew.close()
#delete the .gz version of the file
#os.remove(infile)