Chinaunix首页 | 论坛 | 博客
  • 博客访问: 449662
  • 博文数量: 141
  • 博客积分: 211
  • 博客等级: 入伍新兵
  • 技术积分: 1049
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-17 16:25
个人简介

如此经年,望尽千帆。

文章分类

全部博文(141)

文章存档

2014年(73)

2013年(65)

2012年(3)

我的朋友

分类: Python/Ruby

2014-05-24 22:27:31

在一般都是运用内置函数open()与文件进行交互,下面说说具体用法
在HeadFirstPython网站中下载所有文件,解压后以chapter 3中的“sketch.txt”为例:
 
新建IDLE会话,首先导入os模块,并将工作目录却换到包含文件“sketch.txt”的文件夹,如C:\\Python33\\HeadFirstPython\\chapter3

  1. >>> import os
  2. >>> os.getcwd() #查看当前工作目录
  3. 'C:\\Python33'
  4. >>> os.chdir('C:/Python33/HeadFirstPython/chapter3') #切换包含数据文件的文件夹
  5. >>> os.getcwd() #查看切换后的工作目录
  6. 'C:\\Python33\\HeadFirstPython\\chapter3'
  7. 打开文件“sketch.txt”,读取并显示前两行:
  8. >>> data=open('sketch.txt')
  9. >>> print(data.readline(),end='')
  10. Man: Is this the right room for an argument?
  11. >>> print(data.readline(),end='')
  12. Other Man: I
回到文件起始位置,使用for语句处理文件中的每行,最后关闭文件:

  1. >>> data.seek(0) #使用seek()方法回到文件起始位置
  2. >>> for each_line in data:
  3.     print(each_line,end='')
  4.     
  5. Man: Is this the right room for an argument?
  6. Other Man: I've told you once.
  7. Man: No you haven'
  8. Other Man: Yes I have.
  9. Man: When?
  10. Other Man: Just now.
  11. Man: No you didn't!
  12. Other Man: Yes I did!
  13. Man: You didn'
  14. Other Man: I'm telling you, I did!
  15. Man: You did not!
  16. Other Man: Oh I'm sorry, is this a five minute argument, or the full half hour?
  17. Man: (taking out his wallet and paying) Just the five minutes.
  18. Other Man: Just the five minutes. Thank you.
  19. Other Man: Anyway, I did.
  20. Man: You most certainly did
  21. Other Man: Now let's get one thing quite clear: I most definitely told you!
  22. Man: Oh no you didn'
  23. Other Man: Oh yes I
  24. Man: Oh no you didn't!
  25. Other Man: Oh yes I did!
  26. Man: Oh look, this isn't an
  27. (pause)
  28. Other Man: Yes it
  29. Man: No it isn't!
  30. (pause)
  31. Man: It's just
  32. Other Man: No it isn't!
  33. Man: It IS!
  34. Other Man: It is NOT!
  35. Man: You just contradicted me!
  36. Other Man: No I didn'
  37. Man: You
  38. Other Man: No no
  39. Man: You did just
  40. Other Man:
  41. Man: (exasperated) Oh, this is
  42. (pause)
  43. Other Man: No it isn
读取文件后,将不同role对应数据分别保存到列表man和other:

  1. import os
  2. print(os.getcwd())
  3. os.chdir('C:\Python33\HeadFirstPython\chapter3')
  4. man=[] #定义列表man接收Man的内容
  5. other=[] #定义列表other接收Other Man的内容
  6. try:
  7.     data=open("sketch.txt")
  8.     for each_line in data:
  9.         try:
  10.             (role, line_spoken)=each_line.split(':', 1)
  11.             line_spoken=line_spoken.strip()
  12.             if role=='Man':
  13.                 man.append(line_spoken)
  14.             elif role=='Other Man':
  15.                 other.append(line_spoken)
  16.         except ValueError:
  17.                 pass
  18.     data.close()
  19. except IOError:
  20.     print('The datafile is missing!')
  21. print (man)
  22. print (other)
Tips:
使用open()方法打开磁盘文件时,默认的访问模式为r,表示读,不需要特意指定;
要打开一个文件完成写,需要指定模式w,如data=open("sketch.txt","w"),如果该文件已经存在则会清空现有内容;
要追加到一个文件,需要指定模式a,不会清空现有内容;
要打开一个文件完成写和读,且不清空现有内容,需要指定模式w+;
例如,将上例中保存的man和other内容以文件方式保存时,可修改如下:

  1. import os
  2. print(os.getcwd())
  3. os.chdir('C:\Python33\HeadFirstPython\chapter3')
  4. man=[]
  5. other=[]
  6. try:
  7.     data=open("sketch.txt")
  8.     for each_line in data:
  9.         try:
  10.             (role, line_spoken)=each_line.split(':', 1)
  11.             line_spoken=line_spoken.strip()
  12.             if role=='Man':
  13.                 man.append(line_spoken)
  14.             elif role=='Other Man':
  15.                 other.append(line_spoken)
  16.         except ValueError:
  17.                 pass
  18.     data.close()
  19. except IOError:
  20.     print('The datafile is missing!')
  21. try:
  22.     man_file=open('man.txt', 'w') #以w模式访问文件man.txt
  23.     other_file=open('other.txt','w') #以w模式访问文件other.txt
  24.     print (man, file=man_file) #将列表man的内容写到文件中
  25.     print (other, file=other_file)
  26. except IOError:
  27.     print ('File error')
  28. finally:
  29.     man_file.close()
  30.     other_file.close()
但是第26行print()为什么会报错?“syntax error while detecting tuple”,有大神能给解惑一下?!
阅读(1836) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~