REF 1: https://www.programiz.com/python-programming/file-operation
REF 2: 下載並使用windows 的hexdump
(一)在windows下:
(1) code 7a.py
print("write a.txt as big5 encoding\n") f= open("a.txt",'w',encoding = 'big5') f.write("貓cat\r\n") f.write("狗dog\r\n") f.close()
print("Read a.txt by text mode\n"); f = open("a.txt",'r') print(f.read()) f.close()
print("Read a.txt by binary mode\n"); f = open("a.txt",'r+b') print(f.read()) f.close()
(2) D:\>python 7a.py write a.txt as big5 encoding
Read a.txt by text mode
貓cat
狗dog
Read a.txt by binary mode
b'\xbf\xdfcat\r\r\n\xaa\xafdog\r\r\n'
(3) D:\>type a.txt 貓cat 狗dog
(4)以16進位數顯示檔案內容
D:\>hexdump -C a.txt 000000 bf df 63 61 74 0d 0d 0a aa af 64 6f 67 0d 0d 0a ..cat.....dog...
(二)在Linux下:
(1) code : 7b.py
print("write a.txt as utf-8 encoding\n") f= open("a.txt",'w',encoding = 'utf-8') f.write("貓cat\r\n") f.write("狗dog\r\n") f.close()
print("Read a.txt by text mode\n"); f = open("a.txt",'r') print(f.read()) f.close()
print("Read a.txt by binary mode\n"); f = open("a.txt",'r+b') print(f.read()) f.close()
(2)執行結果
$ /usr/bin/python3.5 7b.py write a.txt as utf-8 encoding
Read a.txt by text mode
貓cat 狗dog
Read a.txt by binary mode
b'\xe8\xb2\x93cat\r\n\xe7\x8b\x97dog\r\n'
(3) $ cat a.txt
貓cat 狗dog
(4)以16進位數顯示檔案內容
$ treehrt ~/python$ hexdump -C a.txt
00000000 e8 b2 93 63 61 74 0d 0a e7 8b 97 64 6f 67 0d 0a |...cat.....dog..| 00000010
(5) 文字模式與二元模式的讀檔迴路程式碼 : 7b2.py
print("write a.txt as utf8 encoding\n") f= open("a.txt",'w',encoding = 'utf-8') f.write("貓cat\r\n狗dog\r\n") f.close()
print("Read a.txt by text mode"); f = open("a.txt",'r') while True: c=f.read(1) if c == "" : break
print(c , end='')
f.close()
print("\nRead a.txt by binary mode"); f = open("a.txt",'rb') for x in f: print(x) f.close()
(6) 7b2.py的執行結果:
$ python3.7 7b2.py write a.txt as utf8 encoding
Read a.txt by text mode 貓cat 狗dog
Read a.txt by binary mode b'\xe8\xb2\x93cat\r\n' b'\xe7\x8b\x97dog\r\n'
|