Python数据类型-文件
2013-05-07 13:41
281 查看
文件也可以看作是Python中的数据类型。当使用Python的内置函数open打开一个文件时,返回一个文件对象。其原型如下所示:
file=open(filename,mode,bufsize)
filename:要打开的文件名。
mode:可选参数,文件打开模式。
mode: 'r'表示以读方式打开文件,'w'表示以写方式打开文件,加入文件存在,则会覆盖源文件,'a'表示'以写方式打开文件,在原文件中添加内容,不会覆盖
rb'表示以二进制读打开文件(读图片),'wb'表示以二进制写打开文件(写图片)
bufsize:可选参数,缓冲区大小。
[b]常用文件操作 [/b]
1.file.read() 将整个文件读入字符串中
#将整个文件一次性读入到内存中
file=open('h:/test.txt','r')
temp = file.read() #temp的类型为字符串
file.close()
2.file.readline() 读取文件的一行到字符串中
#逐行读取文件
file = open('h:/test.txt','r')
temp = file.readline()
while temp:
print temp,
temp=file.readline()
file.close()
#逐行读取文件的另一种方式(推荐)
file = open('h:/test.txt','r')
for line in file:
print line
file.close()
3.file.readlines() 将整个文件读入到列表中
4.file.write() 向文件中写入字符串
file=open('h:/test.txt','a')
content="i write haha"
file.write(content)
file.close()
5.file.writelines() 向文件中写入一个列表
file=open('h:/test.txt','a')
content=['tst1','tst2','\ntet']
file.witelines(content)
file.close()
6.file.close()
file=open(filename,mode,bufsize)
filename:要打开的文件名。
mode:可选参数,文件打开模式。
mode: 'r'表示以读方式打开文件,'w'表示以写方式打开文件,加入文件存在,则会覆盖源文件,'a'表示'以写方式打开文件,在原文件中添加内容,不会覆盖
rb'表示以二进制读打开文件(读图片),'wb'表示以二进制写打开文件(写图片)
bufsize:可选参数,缓冲区大小。
[b]常用文件操作 [/b]
1.file.read() 将整个文件读入字符串中
#将整个文件一次性读入到内存中
file=open('h:/test.txt','r')
temp = file.read() #temp的类型为字符串
file.close()
2.file.readline() 读取文件的一行到字符串中
#逐行读取文件
file = open('h:/test.txt','r')
temp = file.readline()
while temp:
print temp,
temp=file.readline()
file.close()
#逐行读取文件的另一种方式(推荐)
file = open('h:/test.txt','r')
for line in file:
print line
file.close()
3.file.readlines() 将整个文件读入到列表中
4.file.write() 向文件中写入字符串
file=open('h:/test.txt','a')
content="i write haha"
file.write(content)
file.close()
5.file.writelines() 向文件中写入一个列表
file=open('h:/test.txt','a')
content=['tst1','tst2','\ntet']
file.witelines(content)
file.close()
6.file.close()
相关文章推荐
- python3之python的核心数据类型(文件)
- Python核心数据类型——元祖、文件及其他
- 第2章python基础 数据类型与文件操作
- python笔记-数据类型&文件操作
- 【Python】 更多数据类型collections&简易数据文件shelve
- python 将复杂数据类型(list、dict)存储到文件 以及 读入 pickle模块
- Python--使用xlwt将列表类型的数据写到Excel xls文件中--TxtToExcel
- python --- 字符串、数据类型、格式化、文件打开
- python 数据类型:文件
- Python模块之pickle(列表,字典等复杂数据类型与二进制文件的转化)
- Python--将 txt文件里的-字典类型-的数据写到Excel中--xlwt--TxtToExcel
- 05-Python的核心数据类型-元组、文件
- python学习之路-3 初始python数据类型以及文件操作
- python生成CMPL16类型随机定标测试数据并输出到文件
- Python核心数据类型——文件
- Python基础——核心数据类型_文件
- python:如何将txt文件中的数值数据读入到list中,且在list中存在的格式为float类型或者其他数值类型
- python 数据类型 序列——列表
- Python实现将MySQL数据库表中的数据导出生成csv格式文件的方法
- Python学习之路【第二篇】-pyc简介、Python常用的数据类型及其用法和常用运算符