文件
操作文件的函数/方法
在python中要操作文件需要记住的1个函数和3个方法
open函数 :打开文件,并且返回文件操作对象
read :将文件内容读取到内存
write :将指定内容写入文件
close :关闭文件
1.读取文件
open()返回一个文件对象,通常使用两个变量:open(filename,mode)
‘r’ 只读
‘r+’ 读写
‘w’ 只写
file = open('file') ##打开文件(file文件在程序的当前目录,若需要打开指定文件,需要写绝对路径)
f = file.read() ##读取文件
print f
f = file.read()
print f ##第二次读取不到信息,由于文件指针标记由文件头到了文件尾。
##文件指针:
### 文件指针标记从哪个位置开始读取数据
### 第一次打开文件时,通常文件指针会指向文件的开始位置
### 当执行了read方法后,文件指针会移动到读取内容的末尾
file.close() ##如果忘记关闭文件,会造成系统消耗,而且会影响到后续对文件的访问
利用with是一个很好的方法,不需要关闭文件。(程序执行完成后自动释放内存):
with open('file2') as file_object:
text = file_object.read()
print type(text) ##输出文件内容类型
print len(text) ##输出文件内容长度
print text
read方法默认会把文件的所有内容一次性读到内存,如果文件太大,对内存的占用会非常严重。
- readline方法:
readline()方法可以一次性读取一行内容
方法执行后,会把文件指针移动到下一行,准备再次读取
file = open('file')
while True:
text = file.readline()
if not text: ##当读取不出内容时
break
print text,
file.close()
seek() 方法用于移动文件读取指针到指定位置。
fileObject.seek(offset[, whence])
offset – 开始的偏移量,也就是代表需要移动偏移的字节数
whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。
file:
12345678
asas
dsgvcxvfd
f = open('file','r+')
print f.readline()
f.seek(-4,2) ##文件指针偏移到末尾倒数第四个字节(result-->xvf)
#f.seak(5) ##文件指针从开头偏移到第五个字节(result-->678)
print f.read(4) ##从第四个字节开始读取
f.close()
2.写文件:
file = open('file','w') ##覆盖
##file = open('file','a') ##追加字符串
f = file.write('HELLO')
print f
file.close()
with open('file2','w') as file_object:
file_object.write('Every day every morning\n')
file_object.write('My mother my father\n')
3.复制文件
f = open('file')
text = f.read()
w = open('file2','w')
w.write(text)
f.close()
w.close()
file = open('file')
file2 = open('file2','w') ##自定义文件名
while True: ##按行写入
text = file.readline()
file2.write(text)
if not text:
break
print text,
file.close()
file2.close()
JSON文件:
很多程序都要求用户输入某种信息并存储在列表和字典等数据结构中,为了保存这些数据,一种简单的方式是使用模块json来存储。
在python中使用json的时候,json是以一种良好的格式来进行数据的交互,模块json以更简单的数据结构转存到文件中,并在程序再次运行时加载该文件中的数据,还可以使用json在Python程序之间分享数据。更重要的是,json数据格式并非Python专用的,这让你能够将以json格式存储的数据与使用其他编程语言的人分享。
读写Json文件:
import json
number = [1,2,3,43,4]
with open('json_file.json','w') as f_obj:
json.dump(number,f_obj) ##json写入数据
import json
filename = 'json_file.json'
with open(filename) as f_obj:
number = json.load(f_obj) ##读取json文件
print number
实例:保存用户数据
import json
filename = "username.json"
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except ValueError:
username = raw_input("What is you name? ")
with open(filename,"w") as f_obj:
json.dump(username,f_obj)
print "We'll remember you when you come back %s" % username
#依赖于try代码块成功执行的代码都应放到else代码块中:
else: