Python学习笔记ucas(lecture3)文件处理

Lecture 3 文件处理

目录

数据存储可以用数据库、文件
文件:文本文件、二进制文件

处理文件的模块:os os.path shutil

文本文件:

  • 基本是字符串,如python源码、HTML文件都是文本文件
  • 人容易阅读,程序无法直接阅读,且要比二进制文件大

二进制文件:占据内存小,程序可直接阅读

文件常见操作:打开、读写、复制、删除

1文件的创建、打开

这里写图片描述
这里写图片描述
这里写图片描述

2文件的读取

这里写图片描述

3文件的写入、删除

这里写图片描述
这里写图片描述
这里写图片描述

4文件的复制、重命名

这里写图片描述
这里写图片描述

5文件内容的搜索和替换

这里写图片描述

6处理二进制文件

这里写图片描述

7目录的常见操作 os模块、os.path模块

这里写图片描述
这里写图片描述
这里写图片描述

import os
import shutil

f=open('mll.txt','w')
f.write('mll is a student.\n')
f.write('mll is a better man.\n')
f.close()

f=open('mll.txt','a')
f.write('haha!\n')
f.close()

f=open('mll.txt')
while True:
    line=f.readline()
    if line:
        print(line)
    else:
        break
f.close()

print("hello world 1")

f=open('mll.txt')
lines=f.readlines()
for line in lines:
    print(line)
f.close()

print("hello world 2")

f=open('mll.txt')
context=f.read()
print(context)
f.close()

print("hello world 3")

f=open('mll.txt','w+')
context=['hello a\n','hello b\n']
f.writelines(context)
f.close()

print("hello world 4")


open('mll.txt','w')
if os.path.exists('mll.txt'):
    os.remove('mll.txt')

print("hello world 5")

src=open('hello.txt','w')
context=['hello a\n','hello b\n']
src.writelines(context)
src.close()

src=open('hello.txt','r')
dst=open('hello2.txt','w')
dst.write(src.read())
src.close()
dst.close()

print("hello world 6")


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值