使用Python寫檔案的時候,或者將網路資料流寫入到本地檔案的時候,大部分情況下會遇到:UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position ... 這個問題。 網路上有很多類似的檔案講述如何解決這個問題,但是無非就是encode,decode相關的,這是導致該問題出現的真正原因嗎?不是的。 很多時候,我們使用了decode和encode,試遍了各種編碼,utf8,utf-8,gbk,gb2312等等,
執行個體的背景說明假定一個個人資訊系統,需要記錄系統中各個人的故鄉、居住地、以及到過的城市。資料庫設計如下:Models.py 內容如下: from django.db import models class Province(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return self.name class City(models.Model): name =
慚愧啊,今天寫了個尋找子串的Python程式被BS了…如果讓你寫一個程式檢查字串s2中是不是包含有s1。也許你會很直觀的寫下下面的代碼: 代碼如下:#determine whether s1 is a substring of s2 def isSubstring1(s1,s2): tag = False len1 = len(s1) len2 = len(s2) for i in range(0,len2): if s2[i] == s1[0]:
本文執行個體講述了python開啟檔案並擷取檔案相關屬性的方法。分享給大家供大家參考。具體分析如下:下面的代碼通過open函數開啟檔案,並輸出檔案名、開啟狀態、開啟模式等屬性#!/usr/bin/python# Open a filefo = open("foo.txt", "wb")print "Name of the file: ", fo.nameprint "Closed or not : ", fo.closedprint "Opening mode : ",
Python項目中很多時候會需要將時間在Datetime格式和TimeStamp格式之間轉化,又或者你需要將UTC時間轉化為本地時間,本文總結了這幾個時間之間轉化的函數,供大家參考。一、Datetime轉化為TimeStamp def datetime2timestamp(dt, convert_to_utc=False): ''' Converts a datetime object to UNIX timestamp in milliseconds. ''' if isinstance(
最近,我們老大要我寫一個守護者程式,對伺服器處理序進行守護。如果伺服器不幸掛掉了,守護者能即時的重啟應用程式。上網Google了一下,發現Python有很幾個模組都可以建立進程。最終我選擇使用subprocess模組,因為在Python手冊中有這樣一段話: This module intends to replace several other, older modules and functions, such as: os.system、os.spawn*、os.popen*、popen2
最近,想在我的YouMoney(http://code.google.com/p/youmoney/)裡面增加提取使用者作業系統版本資訊。比如windows使用者,可能要返回Windows XP ,或者Windows 2003, 蘋果使用者應該返回Mac OS X 10.5.8。用了很多辦法,包括在mac系統裡調用系統命令,取環境變數,等等。最後無意發現,原來python裡裡面有個platform模組就可以幹這件事情。省事啊!mac上這麼幹 代碼如下:localhost:~ apple$