愤怒中的小草

博客园 首页 新随笔 联系 订阅 管理

读文件 r

要以读文件的模式打开一个文件对象,使用Python内置的open()函数,传入文件名和标示符

写文件 w

写文件和读文件是一样的,唯一区别是调用open()函数时,传入标识符’w’或者’wb’表示写文本文件或写二进制文件:

当我们写文件时,操作系统往往不会立刻把数据写入磁盘,而是放到内存缓存起来,空闲的时候再慢慢写入。只有调用close()方法时,操作系统才保证把没有写入的数据全部写入磁盘。

打开文件的模式有:

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

 "b"表示以字节的方式操作

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

 

class Empty(object):
pass
def sum(a,b):
return a+b
print(sum(3,5))

for i in range(10):
print(i)
print('继续下一个')
break

try:
#以追加的方式写文件
f = open('F:/python/1.txt','a',encoding='gbk',errors='ignore')
f.write('11111111111111\n')
f.write('22222222222222\n')
f.write('北京欢迎你\n')
except FileOpenError:
handlerError(...)
finally:
f.close()

try:
#以只读的模式读取文件 默认
f = open('F:/python/1.txt','r',encoding='gbk')
#通过迭代读取全部文件
for line in f:
print(line)
except FileOpenError:
handlerError(...)
finally:
f.close()

 对list和tuple的学习

L = []
def test():
    for i in range(5):
        print('取数放到数组中')
        print(i)
        L.append(i)


def test2():
    for i in L:
        print('从数组中打印')
        print(i)


if __name__ == '__main__':
    test()
    test2()

print(type(1))
print(type(1.1111))
print(type('str'))
#容器
#list
print(type([1, 1, 1, 'b', 'a', '']))
#tuple
print(type((1, 'a')))
#set
print(type(set(['a', 'b', 2])))
#dict
print(type({'a':1, 'b':3}))

print('list操作演示')
list = [5, 67, 24, 54, 32]
list.sort()
print(min(list))
print(max(list))
for i in list:
    print(i)


list.insert(4,10)
list.append(0)
list.sort()
for i in list:
    print(i)


#tuple元组数据不可更改
print('元组操作')
tple = (1, 44, 'bbb', '', 44)
#统计44 出现的次数
print(tple.count(44))
for i in tple:
    print(i)

 

posted on 2019-01-23 20:24  愤怒中的小草  阅读(160)  评论(0编辑  收藏  举报