作者TW185930 (吱吱)
看板Python
标题[问题] 将字串输出为txt档失败
时间Sun Dec 28 22:40:57 2014
各位大家好,目前对於程式有兴趣(本身非资讯相关科毕)
听闻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://webptt.com/cn.aspx?n=bbs/Python/M.1419777661.A.FC1.html
1F:推 Seudo: man_file.write('\n'.join(man)) 12/28 23:05
2F:推 wlhunag: man_file.write(str(man)) <---将列表直接转为字串 12/28 23:11
先感谢两位大大
其实我是用Python2.7(所以我自己上网找了一下有自行改写),
书上是用Python 3,我想问一下为什麽书上就不用加上这个就能执行呢?
3F:→ 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
4F:→ bibo9901: write 和 print 不一样啊 12/29 00:04
5F:推 alibuda174: from __future__ import print_function 12/29 00:55
6F:→ 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