python 数据类型:文件

来源:互联网 发布:iptv网络电视apk下载 编辑:程序博客网 时间:2024/05/29 12:13

open(filename,mode,bufsize)

其参数的意义:

filename:要打开的文件;

mode:可选参数,文件打开的模式。'r' 只读方式打开,'w'写方式打开,'b'表示以二进制方式打开

bufsize: 可选参数,缓冲区大小。

常用的文件操作函数如下:

file.read()  将整个文件读入字符串中

file.readline()  读入文件中的一行字符串

file.readlines()  将整个文件按行读入列表中。

file.write()  向文件中写入字符串

file.writelines() 向文件中写入一个列表

file.close() 关闭打开的文件

[c-sharp] view plaincopyprint?
  1. >>> str 
  2. 'abcdefg' 
  3. >>> file = open('c:/python.txt','w'
  4. >>> file.write('python') #向文件中写入字符串 
  5. >>> a = []               #定义一个空的列表 
  6. >>> for i in range(7): 
  7. ...     s = str[i] + '/n 
  8.   File "<stdin>", line 2 
  9.     s = str[i] + '/n 
  10.                    ^ 
  11. SyntaxError: EOL while scanningstring literal 
  12. >>> for i in range(7): 
  13. ...     s = str[i] + '/n' 
  14. ...     a.append(s) 
  15. ... 
  16. >>> file.writelines(a) #将列表写入文件 
  17. >>> file.close() 
  18. >>> file = open('c:/python.txt','r'
  19. >>> s = file.read()  #将整个文件读入字符串中 
  20. >>> print s 
  21. pythona 
  22.  
  23. >>> file.close() 
  24. >>> file = open('c:/python.txt','r'
  25. >>> l = file.readlines() #将文件读取到列表中 
  26. >>> print l 
  27. ['pythona/n', 'b/n','c/n', 'd/n','e/n', 'f/n','g/n'