1、从文件中读取数据
1、1 读取整个文件
with open('digits.txt') as file_object:
contents=file_object.read()
print contents.rstrip()
1)在文件所在目录建立文件digits.txt后,函数open()打开文件存储到变量file_object中
2)关键字with在不需要访问文件后将其关闭
3)有了文件对象后,使用方法read()读取整个文件,将其作为一个字符串存储到变量contens中。
4)read()到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一个空行。要删除末尾的空行,可使用方法rstrip()
1、2 文件路径
with open('/home/qq/python_work/digits.txt') as file_object:
for line in file_object:
print line.rstrip()
open()中使用绝对路径来打开文件
1、3逐行读取文件
with open('digits.txt') as file_object:
for line in file_object:
print line.rstrip()
1)在文件所在目录建立文件digits.txt后,函数open()打开文件存储到变量file_object中
2)使用循环来遍历文件每一行的内容
1、4 创建一个包含文件各行内容的列表后使用文件的内容
with open('digits.txt') as file_object:
lines=file_object.readlines()
new_lines=[]
for line in lines:
new_lines.append(line.rstrip())
print new_lines
1)方法readlines()从文件中读取每一行,将其存储在一个列表中,该列表被存储到变量lines中,接下来建立一个空列表,使用循环遍历列表lines,并将其元素添加到新的列表
new_lines中,打印新列表。
2)读取文本文件时,Python将其中的所有文本都解读为字符串。如果读取的是数字,需要使用int()将其转换为整数
2、写入文件
2、1 写入多行内容
name='a.txt'
with open(name,'w') as file_object:
file_object.write('fffffffff\n')
file_object.write('aaaaaaaaa\n')
2)如果要写入的文件不存在,函数open()将自动创建他
3)以写入模式'w'打开文件时,如果指定的文件已经存在,Python将在返回文件对象前清空该文件
4)函数write()不会再写入文本末尾添加换行符
5)如果要添加文件内容,而不是覆盖原有的内容,可以附加模式打开文件。
name='a.txt'
with open(name,'w') as file_object:
file_object.write('fffffffff\n')
file_object.write('aaaaaaaaa\n')
with open(name,'a') as file_object:
file_object.write('bbbbbbbbb\n')
file_name='guest.txt'
while True:
with open(file_name,'a') as file_object:
message=raw_input('enter your name:')
if message=='quite':
break
file_object.write(message)
with open('guest.txt') as file_object:
print file_object.read()
3、 异常
3、1 使用try--except--else代码块
while True:
first_num=raw_input('enter first num is:')
if first_num=='q':
break
second_num=raw_input('enter second num is:')
if second_num=='q':
break
try:
result=int(first_num)/int(second_num)
except ZeroDivisionError:
print 'your can not do it'
else:
print result
1)只有可能引发异常的代码才需要放在try语句中
2)如果try代码块中的代码运行起来没有问题,Python将跳过except代码块,若try代码块中的代码导致了错误,Python将查找这样的except代码块,并运行其中的代码
3)依赖于try代码块成功执行的代码都应该放到else代码块中
4、使用json模块来存储数据
import json
names=['zhao','qian','sun','li','wang']
filename='name.json'
with open(filename,'w') as f_ob:
json.dump(names,f_ob)
with open(filename) as f_ob:
print json.load(f_ob)
1)函数json.dump()接受两个实参:要存储的数据以及用于存储数据的文件对象。
2)通常使用文件扩展名.json来指出文件存储的数据格式为JSON格式。
3)使用json.load()将文件读取到内存中。