推 Seudo: man_file.write('\n'.join(man)) 12/28 23:05
推 wlhunag: man_file.write(str(man)) <---將列表直接轉為字串 12/28 23:11
先感謝兩位大大
其實我是用Python2.7(所以我自己上網找了一下有自行改寫),
書上是用Python 3,我想問一下為什麼書上就不用加上這個就能執行呢?
→ alibuda174: 確定嗎?你的程式不論2or3,都會出錯 12/28 23:37
目前照著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
→ bibo9901: write 和 print 不一樣啊 12/29 00:04
推 alibuda174: from __future__ import print_function 12/29 00:55
→ alibuda174: 2.x與3.x的print 不一樣 這行可讓2.x使用3.x的print 12/29 00:56
感謝a大,加了這段真能在2.7執行耶~~~@@
請問怎知到這些額外功能在哪裡看阿?@@
※ 編輯: TW185930 (140.128.121.135), 12/29/2014 08:14:21