python中怎么将数据保存到⽂件中_【Python实战06】保存数
据到⽂件中
之前我们从⽂件中进⾏读取数据,并把读取到的数据进⾏了简单的处理,然后通过print语句进⾏了打印。但是很多时候我们是需要把处理后的数据保存到⽂件中的,所以这⾥我们接着介绍如何把处理后的数据保存到⽂件,因为在之前只是对数据进⾏了⾮常简单的处理,这⾥⾸先对数据做⼀些复杂的处理。
程序处理数据
编写⼀段代码实现以下功能:创建两个名为man和other的空列表,读取⽂件中的内容(此⽂件在【Python实战04】中有),并使⽤“:”进⾏分割,分别保存为role和line_spoken,然后通过role为man或者other,将对应说的内容分别保存到对应的man和other列表中。
代码如下:
man= []
other = []
try:
data = open('')
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!')
print(man)
print(other)
运⾏结果如下: >>> ================================ RESTART ================================
>>>
['Is this the right room for an argument?', "No you haven't!", 'When?', "No you didn't!", "You didn't!", 'You did not!', 'Ah! (taking out his wallet and paying) Just the five minutes.', 'You most certainly did not!', "Oh no you didn't!", "Oh no you didn't!", "Oh look, this isn't an argument!", "No it isn't!", "It's just contradiction!", 'It IS!', 'You just contradicted me!', 'You DID!', 'You did just then!', '(exasperated) Oh, this is futile!!', 'Yes it is!']
["I've told you once.", 'Yes I have.', 'Just now.', 'Yes I did!', "I'm telling you, I did!", "Oh I'm sorry, is this a five minute argument, or the full half hour?", 'Just the five minutes. Thank you.', 'Anyway, I did.', "Now let's get one thing quite clear: I most
definitely told you!", 'Oh yes I did!', 'Oh yes I did!', 'Yes it is!', "No it isn't!", 'It is NOT!', "No I didn't!", 'No no no!', 'Nonsense!', "No it isn't!"]
>>>
接着我们要做的⼯作就是把列表man和other中的内容保存到⽂件,⾸先就是要以写的⽅式打开⼀个⽂件。
以写模式打开⼀个⽂件
代码如下:
out = open('','w')
这⾥我们以写的模式打开了,然后我们可以通过以下语句将内容写到这个⽂件,如下:
print('Hello World',file=out)
这样我们就把Hello World这个字符串写⼊到了⽂件中去了,最后别忘了关闭流:
out.close()
然后我们就可以改写之前的代码,将man和other列表的内容分别保存⾄和中,代码如下: man= []
other = []
try:
data = open('')
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!')
print(man)
print(other)
try:
man_file = open('','w')
other_file = open('','w')
print(man,file=man_file)
print(other,file=other_file)
man_file.close()
other_file.close()
except IOError:
print('File Error')
可以看到我们只是在之前的代码最后加⼊了⽂件的写操作,其他的代码并没有改动。执⾏以上的代码,可以发现在对应的⽂件夹中⽣成了⼀下的两个⽂件:
两个⽂件的内容分别如下:
: ['Is this the right room for an argument?', "No you haven't!", 'When?', "No you didn't!", "You didn't!", 'You did not!', 'Ah! (taking out his wallet and paying) Just the five minutes.', 'You most certainly did not!', "Oh no you didn't!", "Oh no you didn't!", "Oh look, this isn't an argument!", "No it isn't!", "It's just contradiction!", 'It IS!', 'You just contradicted me!', 'You DID!', 'You did just then!', '(exasperated) Oh, this is futile!!', 'Yes it is!']
: ["I've told you once.", 'Yes I have.', 'Just now.', 'Yes I did!', "I'm telling you, I did!", "Oh I'm sorry, is this a five minute argument, or the full half hour?", 'Just the five minutes. Thank you.', 'Anyway, I did.', "Now let's get one thing quite clear: I most definitely told you!", 'Oh yes I did!', 'Oh yes I did!', 'Yes it is!', "No it isn't!", 'It is NOT!', "No I didn't!", 'No no no!',
'Nonsense!', "No it isn't!"]
但是此时我们的代码相对脆弱,因为在最后进⾏⽂件关闭时,如果第⼀个man_file.close()执⾏错误的话,则第⼆个other_file.close()则不会被执⾏,此时就导致了other_file的关闭失败,此时我们可以通过finally语句进⾏限制。
⽤finally拓展try
这⾥我们可以把数据关闭操作直接放置到finally语句中进⾏操作,如下:
man= []
other = []
try:
data = open('')
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!')
print(man)
print(other)
try:
man_file = open('','w')
other_file = open('','w')
print(man,file=man_file)
print(other,file=other_file)
except IOError:
print('File Error')
finally:
man_file.close()
other_file.close()
运⾏结果是和之前⼀样的,同样会⽣成对应的两个⽂件,不同的是处理错误的能⼒增强了。
补充:
这⾥我们也可以对错误类型的详细信息进⾏打印,⽐如打开⽂件进⾏读取时,我们可以打印当前错误的详细信息,代码如下:
try:
data = open('')
except IOError as err:
print('File Error:'+str(err))
这⾥为IOError异常起了⼀个别名err,并打印err中的内容,因为err为⼀个对象,所以使⽤str函数来打印对象的具体内容。结果如下:>>> ================================ RESTART ================================
>>>
File Error:[Errno 2] No such file or directory: ''
>>>
这⾥就直接提⽰说当前没有到⽂件。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论