[問題] 將字串輸出為txt檔失敗

看板Python作者 (吱吱)時間9年前 (2014/12/28 22:41), 9年前編輯推噓3(304)
留言7則, 4人參與, 最新討論串1/1
各位大家好,目前對於程式有興趣(本身非資訊相關科畢) 聽聞python對於新手來說比較容易入門,故自行去圖書館 借了一本深入淺出Python一書來練習,不過最近一直卡關 了,這本書中第四章是在講將文字串輸出為txt檔保存 ,可是我發現我寫出來的程式沒辦法將文字串存入txt檔 (雖 然會創造出程式中命名的txt檔,但是裡面是空的),而執行程式 會出現 Traceback (most recent call last): File "C:\Users\SONY\Desktop\python test\chapter4\page112.py", line 26, in <module> man_file.write(man) TypeError: expected a character buffer object 的錯誤,我後來試著找問題發現是因為我的字串是清單所以沒法 寫進txt檔,請問我要怎麼改呢~__~? (我有點不太會描述,希望大家懂我的問題點Orz) 以下為我的程式: man = [] other = [] try: data = open('sketch.txt') for each_line in data: try: (role, line_spoken) = each_line.split(':', 1) line_spoken = line_spoken.strip() if role == 'Man': man.append(line_spoken) elif role == 'Other Man': other.append(line_spoken) except ValueError: pass data.close() except IOError: print 'The datafile is missing!' try: man_file = open('man_data.txt', 'w') other_file = open('other_data.txt', 'w') man_file.write(man) other_file.write(other) except IOError: print 'File error.' finally: man_file.close() other_file.close() -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.118.247.42 ※ 文章網址: http://www.ptt.cc/bbs/Python/M.1419777661.A.FC1.html

12/28 23:05, , 1F
man_file.write('\n'.join(man))
12/28 23:05, 1F

12/28 23:11, , 2F
man_file.write(str(man)) <---將列表直接轉為字串
12/28 23:11, 2F
先感謝兩位大大 其實我是用Python2.7(所以我自己上網找了一下有自行改寫), 書上是用Python 3,我想問一下為什麼書上就不用加上這個就能執行呢?

12/28 23:37, , 3F
確定嗎?你的程式不論2or3,都會出錯
12/28 23:37, 3F
目前照著1F 及2F 大大們建議能成功把字串存入txt檔了 書上的程式前半段(標色處)都是一樣的,後半段是因為2.7關係所以 我改用.write,不過如alibuda174所說的,書上程式碼原封不動改用python3 下去跑,也會error~_~。 以下是書中原始程式碼: man = [] other = [] try: data = open('sketch.txt') for each_line in data: try: (role, line_spoken) = each_line.split(':', 1) line_spoken = line_spoken.strip() if role == 'Man': man.append(line_spoken) elif role == 'Other Man': other.append(line_spoken) except ValueError: pass data.close() except IOError: print('The datafile is missing!') try: man_file = open('man_data.txt', 'w') other_file = open('other_data.txt', 'w') print(man, file=man_file) print(other, file=other_file) except IOError: print('File error.') finally: man_file.close() other_file.close() ※ 編輯: TW185930 (122.118.247.42), 12/28/2014 23:58:22 ※ 編輯: TW185930 (122.118.247.42), 12/29/2014 00:00:03

12/29 00:04, , 4F
write 和 print 不一樣啊
12/29 00:04, 4F

12/29 00:55, , 5F
from __future__ import print_function
12/29 00:55, 5F

12/29 00:56, , 6F
2.x與3.x的print 不一樣 這行可讓2.x使用3.x的print
12/29 00:56, 6F
感謝a大,加了這段真能在2.7執行耶~~~@@ 請問怎知到這些額外功能在哪裡看阿?@@ ※ 編輯: TW185930 (140.128.121.135), 12/29/2014 08:14:21

12/29 08:49, , 7F
12/29 08:49, 7F
文章代碼(AID): #1Ke1Pz_1 (Python)