您的位置:首页 > 编程语言 > Python开发

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

2018-02-02 12:43 615 查看

Lecture 3 文件处理

目录

Lecture 3 文件处理

目录
1文件的创建打开

2文件的读取

3文件的写入删除

4文件的复制重命名

5文件内容的搜索和替换

6处理二进制文件

7目录的常见操作 os模块ospath模块

数据存储可以用数据库、文件

文件:文本文件、二进制文件

处理文件的模块: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")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: