Python学习笔记(五)

python学习网 2017-09-19 09:53:12

Python学习笔记(五):

  1. 文件操作
  2. 另一种文件打开方式-with
  3. 作业-三级菜单高大上版

1. 知识点

  1. 能调用方法的一定是对象
  2. 涉及文件的三个过程:打开-操作-关闭
  3. python3中一个汉字就是一个字符

2. 文件操作

  • 模式:
  1. 读 r(光标默认在开始)
    1. 写 w(先清空)
    2. 追加a(光标默认在最后)
    3. 读写r+(光标默认在开始)
    4. 写读w+(先清空)
    5. 追加读a+(光标默认在最后)
  2. 读文件
file = open('1.txt','r',encoding='utf8')    #打开为文件
data = file.read()                          #读取文件
data = file.read(5)                         #读取五个字符
print(data)
file.close()                                #关闭文件
  1. 写文件
file = open('1.txt','w',encoding='utf8')
data = file.write('hello world')
file.close()
  1. 追加
file = open('2.txt','a',encoding='utf8')
data = file.write('hello world\n')
file.close()
  1. 光标位置检测-tell
file = open('1.txt','r',encoding='utf8')    #打开为文件
print(file.tell())                          #输出光标当前位置
data = file.read(5)                         #读取五个字符
print(file.tell())                          #输出光标当前位置
file.close()                                #关闭文件
  1. 光标位置移动-seek
file = open('1.txt','r',encoding='utf8')    #打开为文件
print(file.tell())                          #输出光标当前位置
data = file.read(5)                         #读取五个字符
print(file.tell())                          #输出光标当前位置
file.seek(0)                                #光标重置
print(file.read(4))                         #读取四个字符
file.close()                                #关闭文件
  1. 将内存的内容输出到硬盘-flush
  2. 截断-truncate

3. 另一种文件打开方式-with

f = open('1.txt','r')
f.read()
f.close()

with open('1.txt','r') as f:
    f.read()

with open('1.txt','r') as f_read,open('2.txt','w') as f_write:
    for line in f_read:
        f_wirte.write(line)

4. 作业-三级菜单高大上版

作业要求

阅读(917) 评论(0)