我是新來的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)