1.寫中文資料到檔案
1 2 3 4 | fp=open("test.txt", "w", encoding = "UTF-8") fp.write("好吃芋頭在雲林縣林內鄉烏塗村\n") fp.write("好吃花生在雲林縣元長鄉和虎尾鎮") fp.close() |
2.讀取資料
1 2 3 4 5 | fp=open("test.txt", "r", encoding = "UTF-8") lines=fp.readlines() for line in lines: print(line) fp.close() |
執行結果:
好吃芋頭在雲林縣林內鄉烏塗村
好吃花生在雲林縣元長鄉和虎尾鎮
3.檔案已有換行字元'\n',輸出可以不用換行
1 2 3 4 5 | fp=open("test.txt", "r", encoding = "UTF-8") lines=fp.readlines() for line in lines: print(line, end="") fp.close() |
執行結果:
好吃芋頭在雲林縣林內鄉烏塗村
好吃花生在雲林縣元長鄉和虎尾鎮
4.使用with/as來讀取檔案內容
1 2 3 4 5 | with open("test.txt", "r", encoding = "UTF-8") as fp: lines=fp.readlines() for line in lines: print(line, end="") fp.close() |
1 2 3 4 5 6 7 8 | with open("test.txt", "r", encoding = "UTF-8") as fp: lines = fp.read().split("\n") line_cnt = len(lines) word_cnt = char_cnt = 0 for line in lines: words = line.split() word_cnt, char_cnt = word_cnt + len(words), char_cnt + len(line) print("File {0} has {1} lines, {2} words, {3} characters".format("test.txt", line_cnt, word_cnt, char_cnt)) |
File test.txt has 2 lines, 2 words, 29 characters
眼尖的朋友是否覺得有問題呢?
中文字數不能用split()來計算,29字元數就是中文字數。
沒有留言:
張貼留言