PTT
Submit
Submit
選擇語言
正體中文
简体中文
PTT
Python
[問題] 將字串輸出為txt檔失敗
作者:
TW185930
(吱吱)
2014-12-28 22:40:57
各位大家好,目前對於程式有興趣(本身非資訊相關科畢)
聽聞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()
作者:
Seudo
(進擊的三笠)
2014-12-28 23:05:00
man_file.write('\n'.join(man))
作者: wlhunag (阿龍)
2014-12-28 23:11:00
man_file.write(str(man)) <---將列表直接轉為字串
作者:
alibuda174
(阿哩不達)
2014-12-28 23:37:00
確定嗎?你的程式不論2or3,都會出錯
作者:
bibo9901
(function(){})()
2014-12-29 00:04:00
write 和 print 不一樣啊
作者:
alibuda174
(阿哩不達)
2014-12-29 00:55:00
from __future__ import print_function2.x與3.x的print 不一樣 這行可讓2.x使用3.x的print
http://goo.gl/SmHiaf
繼續閱讀
Re: [閒聊] python web framework
Neisseria
[閒聊] python web framework
yshihyu
[問題] html 的 frameset
gn00618777
[問題] Pypy3 import uuid
os653
[問題] Flask 和 HTML
gn00618777
Fw: [徵才] 購明系雲 徵 前端 與 Python 後端
keitheis
[問題] 單獨用 django 的 template
kobenein
[問題] Flask running
gn00618777
[問題] 請問list怎麼一次印n個item
liataian
Re: [問題]scrapy如何將item的資料成對的儲存起來?
allen511081
Links
booklink
Contact Us: admin [ a t ] ucptt.com