4 持久存储:文件存储、读写
数据保存到文件:在学习的过程中出现了一个问题,老是报一个错:SyntaxError: invalid syntax;
这个是语法错误,后来搜了下才知道是python2.7和python3.5并不兼容,因为之前一直是在ubuntu的终端里
写这些简单的实例,后来程序稍微大点就不方便了,就安装了idle,用命令:sudo apt-get install idle,安装完启动后,
载入python文件,然后运行发现是python2.7,然后逐行运行,发现报错,而之前这些代码都是没问题的,后来重新安
装idle3,命令:sudo apt-get install idle3,然后启动:idle3,运行实例代码,没有问题。
实例一:
1 Python 3.5.2 (default, Nov 17 2016, 17:05:23) 2 [GCC 5.4.0 20160609] on linux 3 Type "copyright", "credits" or "license()" for more information. 4 >>> import os 5 >>> os.getcwd() 6 '/home/user' 7 >>> os.chdir('/home/user/project/python_model/HeadFirstPython/chapter3') 8 >>> os.getcwd() 9 '/home/user/project/python_model/HeadFirstPython/chapter3' 10 >>> man=[] 11 >>> other=[] 12 >>> try: 13 data=open('sketch.txt') 14 for each_line in data: 15 try: 16 (role,line_spoken)=each_line.split(':',1) 17 line_spoken=line_spoken.strip() 18 if role=='Man': 19 man.append(line_spoken) 20 elif role=='Other Man': 21 other.append(line_spoken) 22 except ValueError: 23 pass 24 data.close() 25 except IOError: 26 print('The datafile is missing!') 27 28 29 >>> print(man) 30 ['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!'] 31 >>> print(other) 32 ["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!"] 33 >>>