python 鏂囦欢璇诲啓鏃剁敤open杩樻槸codecs.open

聽聽聽聽www.cscodewrite.com聽 聽聽

聽 聽 聽褰撴垜闈㈡湁鏁版嵁闇�瑕佷繚瀛樻椂锛岀涓�鏃堕棿涓�鑸細鎯冲埌鍐欏埌涓�涓猼xt鏂囦欢涓紝褰撶劧锛屾暟鎹噺姣旇緝澶х殑鏃跺�欒繕鏄啓鍒版暟鎹簱姣旇緝鏂逛究绠$悊锛岄渶瑕佽繘琛岀綉缁滀紶杈撴椂瑕佸簭鍒楀寲锛宩son鍖栥�備笅闈富瑕佹暣鐞嗕竴涓嬪钩鏃剁敤鐨勬渶澶氱殑鍐欏叆鍒版枃浠朵腑锛屼竴鑸互txt缁撳熬锛宭inux閲屼笉浼氫互鍚庣紑鏉ュ尯鍒嗘枃浠剁被鍨嬶紝鍚庣紑鍙互闅忎究锛屼篃鍙互娌℃湁銆�

聽聽聽聽聽 python璇诲啓鏂囦欢浼拌澶у閮界敤open鍐呯疆鍑芥暟锛屾垨鑰協ile杩欎釜宸ュ巶鍑芥暟锛岃繖涓や釜鐨勬晥鏋滃熀鏈竴鏍枫��

鎵撳紑鏂囦欢鐨勬柟寮忎竴鑸负锛歠=open(file_name,access_mode =聽'r',buffering = -1)銆俧ile_name灏辨槸鏂囦欢鐨勮矾寰勫姞鏂囦欢鍚嶅瓧锛屼笉鍔犺矾寰勫垯鏂囦欢浼氬瓨鏀惧湪python绋嬪簭鐨勮矾寰勪笅锛�

access_mode灏辨槸鎿嶄綔鏂囦欢鐨勬ā寮忥紝涓昏鏈塺,w,rb锛寃b绛夛紝缁嗚妭缃戜笂涓�澶у爢,buffering = -1鏄敤浜庢寚绀鸿闂枃浠舵墍閲囩敤鐨勭紦瀛樻柟寮忋��0琛ㄧず涓嶇紦瀛橈紱1琛ㄧず鍙紦瀛樹竴琛岋紝n浠h〃缂撳瓨n琛屻�傚鏋滀笉鎻愪緵鎴栦负璐熸暟锛屽垯浠h〃浣跨敤绯荤粺榛樿鐨勭紦瀛樻満鍒躲��

聽聽聽聽聽 鎵撳紑浠ュ悗灏辨槸鍐欏拰璇荤殑鎿嶄綔銆備絾鏄敤open鏂规硶鎵撳紑浼氭湁涓�浜涢棶棰樸�俹pen鎵撳紑鏂囦欢鍙兘鍐欏叆str绫诲瀷,涓嶇瀛楃涓叉槸浠�涔堢紪鐮佹柟寮忋�備緥濡�

>>> fr = open('test.txt','a')

>>> line1 = "鎴戠埍绁栧浗"

>>> fr.write(line1)

杩欐牱鏄畬鍏ㄥ彲浠ョ殑銆備絾鏄湁鏃跺�欐垜浠埇铏垨鑰呭叾浠栨柟寮忓緱鍒颁竴浜涙暟鎹啓鍏ユ枃浠舵椂浼氭湁缂栫爜涓嶇粺涓�鐨勯棶棰橈紝鎵�浠ュ氨涓�鑸兘缁熶竴杞崲涓簎nicode銆傛鏃跺啓鍏pen鏂瑰紡鎵撳紑鐨勬枃浠跺氨鏈夐棶棰樹簡銆備緥濡�

>>> line2 = u'鎴戠埍绁栧浗'

>>> fr.write(line2)

Traceback (most recent call last):

File "", line 1, in

fr.write(line2)

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-11: ordinal not in range(128)

>>>聽

鎬庝箞鍔烇紝鎴戜滑鍙互灏嗕笂闈㈢殑line2缂栫爜鎴恠tr绫诲瀷锛屼絾鏄お楹荤儲銆傛垜浠鎶婂緱鍒扮殑涓滆タ鍏坉ecode涓簎nicode鍐峞ncode涓簊tr銆傘�傘��

input鏂囦欢(gbk, utf-8...)聽 聽----decode----->聽 聽unicode聽聽-------encode------> output鏂囦欢(gbk, utf-8...)

浠f浛杩欑箒鐞愮殑鎿嶄綔灏辨槸codecs.open锛屼緥濡�

>>> import codecs

>>> fw = codecs.open('test1.txt','a','utf-8')

>>> fw.write(line2)

>>>聽

涓嶄細鎶ラ敊锛岃鏄庡啓鍏ユ垚鍔熴�傝繖绉嶆柟娉曞彲浠ユ寚瀹氫竴涓紪鐮佹墦寮�鏂囦欢锛屼娇鐢ㄨ繖涓柟娉曟墦寮�鐨勬枃浠惰鍙栬繑鍥炵殑灏嗘槸unicode銆傚啓鍏ユ椂锛屽鏋滃弬鏁� 鏄痷nicode锛屽垯浣跨敤open()鏃舵寚瀹氱殑缂栫爜杩涜缂栫爜鍚庡啓鍏ワ紱濡傛灉鏄痵tr锛屽垯鍏堟牴鎹簮浠g爜鏂囦欢澹版槑鐨勫瓧绗︾紪鐮侊紝瑙g爜鎴恥nicode鍚庡啀杩涜鍓嶈堪 鎿嶄綔銆傜浉瀵瑰唴缃殑open()鏉ヨ锛岃繖涓柟娉曟瘮杈冧笉瀹规槗鍦ㄧ紪鐮佷笂鍑虹幇闂銆�


鎬荤粨涓�涓嬶細鏂囦欢璇诲敖閲忕敤绗簩绉嶆柟娉曪紝涓�鑸笉浼氬嚭鐜扮紪鐮佺殑闂銆傝嚦浜庣敤绗簩绉嶆柟娉曟湁浠�涔堢己鐐癸紝鎴戞病鏈夌爺绌惰繃銆傘��

你可能感兴趣的:(python 鏂囦欢璇诲啓鏃剁敤open杩樻槸codecs.open)