从文件中读取数据:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
关键字with 在不再需要访问文件后将其关闭
要删除多出来的空行,可在print 语句中使用rstrip() :
print(contents.rstrip())
读取一行
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
用readline会读取一行组成列表,readlines会读取每一行最后组成列表
写文件
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
open文件方式:默认为r,写为w,追加为a
异常处理:
处理ZeroDivisionError 异常
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
捕获异常,和处理异常
FileNotFoundError异常
方法split() 以空格为分隔符将字符串分拆成多个部分,并将这些部分都存储到一个列表中
filename=raw_input("请输入文件路径:")
try:
with open(filename) as file_obj:
contents=file_obj.read()
file_list=list(contents)
print str(len(file_list))+"Byte"
contents=contents.split()
print str(len(contents))+"个单词数"
except :
print "open file filed"
pass 语句 一声不响的继续运行下去
str.count()会返回字符串的长度