各位大家好,目前對於程式有興趣(本身非資訊相關科畢)
聽聞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()