2021-09-08 python基础知识学习:文件操作和os模块

1.文件操作(IO技术)

(1)打开文件

f = open(文件名[,打开方式])
在这里插入图片描述

#文件写入
f  = open('a.txt','a')#新建一个文件,a,文件不存在则创建
s = 'slene\nbai\n'
f.write(s)#把字符串写在文件里
f.close()

在这里插入图片描述

(2)编码

windows操作系统是GBK,python用Unicode编码
在这里插入图片描述

f  = open('a.txt','w',encoding='UTF-8')#UTF-8新建一个文件,中文久不会乱码
s = 'slene\nbai\n啦啦啦啦啦'
f.write(s)
f.close()
'''结果
slene
bai
啦啦啦啦啦
'''
(3)close()关闭文件流
s = 'baibaibai'
with open('a.txt','w') as f:
    f.write(s)
#或者
try:
    s = 'baibaibai'
    f = open('b.txt','w')
    f.write(s)
except BaseException as e:
    print(e)
finally:
    f.close()
(4)文本文件读取
#读取前面5个字符
with open('a.txt','r',encoding='gbk') as f:
    print(f.read(5))

#使用迭代器(每次返回一行)读取文本文件
with open('a.txt','r',encoding='gbk') as f:
    for a in f:
        print(a,end='')

#一行一行读取
with open('a.txt','r',encoding='gbk') as f:
    while True:
        fragment = f.readline()
        if not fragment:
            break
        else:
            print(fragment,end='')
#把文本文件中的每行都标上行号
with open('a.txt','r') as f:
    lines = f.readlines()
    lines = [temp.rstrip() + '#'+str(index)+'\n' for index,temp in enumerate(lines)]#推导式生成列表
with open('a.txt','w') as f:
    f.writelines(lines)
    #.rstrip() 去掉换行符
(5)二进制文件的读写

不加b,默认是文本文件
在这里插入图片描述

#拷贝一张图片
with open('D:\\photo\\Saved Pictures\\a.jpg','rb') as f:
    with open('a.copy.jpg','bw') as w:
        for line in f.readlines():
            w.write(line)
print('finnish copy')
(6)文件对象常用的方法和属性

在这里插入图片描述
在这里插入图片描述

# -*- coding: GBK -*-
with open('b.txt','r') as f:
    print('文件名是:{}'.format(f.name))
    print('指针当前位置:',f.tell())
    print('读取的一行内容:',str(f.readline()))
    print('读完后指针现在的位置:',f.tell())
    f.seek(7)  #指针偏移到第7个字符
    print('读取的一行内容:', str(f.readline()))
'''结果:
文件名是:b.txt
指针当前位置: 0
读取的一行内容: People may wonder why different words are used to describe these four countries:

读完后指针现在的位置: 82
读取的一行内容: may wonder why different words are used to describe these four countries:
'''
(7)使用pickle序列化

序列化指将对象转化成串行化数字形式
在这里插入图片描述

# -*- coding: GBK -*-
import pickle
a1 = 'bai'
a2 = 234
a3 = [20, 30, 40]
with open('data.dat','wb') as f:
#序列化
    pickle.dump(a1,f)
    pickle.dump(a2,f)
    pickle.dump(a3,f)

with open('data.dat','rb') as f:
    b1 = pickle.load(f)
    b2 = pickle.load(f)
    b3 = pickle.load(f)
    print(b1);print(b2);print(b3)
(8)csv文件的操作
# -*- coding: GBK -*-
import csv
with open('table1.csv','r') as f:
    a_csv = csv.reader(f)    #reader方法
    print(list(a_csv))       #一个列表
    for row in a_csv:
        print(row)
'''
[['id', 'name', 'age', 'salary'], ['1', 'bai', '18', '5000'], ['2', 'selene', '19', '8000'], ['3', 'tutu', '20', '10000']]
'''
#后面的循环不能打印,因为前面readerh之后,指针到了最后
# -*- coding: GBK -*-
import csv
with open('table1.csv','r') as f:
    a_csv = csv.reader(f)
    for row in a_csv:
        print(row)
'''
['id', 'name', 'age', 'salary']
['1', 'bai', '18', '5000']
['2', 'selene', '19', '8000']
['3', 'tutu', '20', '10000']
'''
#去掉前面的,就可以打印了
#写入表格
with open('table2.csv','w') as f:
    b_csv = csv.writer(f)
    b_csv.writerow(['id', '姓名', '年龄'])
    b_csv.writerow(['01', '白', '24'])
    b_csv.writerow(['02', '白2', '25'])

2.os和os.path模块

(1)os模块
# -*- coding: GBK -*-
import os
#os.system('notepad.exe')#调用记事本程序
#os.system('regedit')#调用注册表
#os.system('cmd')

#直接调用可执行的程序(微信)
os.system(r'D:\\APP\\weixin\\WeChat\\WeChat.exe')
(2)文件和目录操作

在这里插入图片描述
在这里插入图片描述

# -*- coding: GBK -*-
import os
######获取文件和文件夹相关信息#######
print(os.name) #获得操作系统的信息,windows--nt,linux--posix
print(os.sep)#分隔符,windows--\,linux--/
print(repr(os.linesep))
print(os.stat('python148.py'))#文件所有属性
######关于作目录的操作#######
print(os.getcwd())  #获取当前文件工作目录
os.mkdir('book')     #在当前工作目录前新建一个文件夹
os.chdir('d:')      #改变当前工作目录
######创建目录、#######
os.mkdir('book1')   #建立目录
os.rmdir('book1')
os.makedirs('电影/美剧')   #建立多级目录
os.removedirs('电影/美剧')
os.makedirs('电影/美剧/老友记')
os.makedirs('../电影/韩剧/朴信惠')   #..指上一级目录
dir = os.listdir('电影')     #返回'电影'下一级目录名,这里是美剧
print(dir)
(3)os.path模块

在这里插入图片描述

# -*- coding: GBK -*-
import os
import os.path
print(os.path.isabs('D:/pytorch_learning'))  #是否是绝对路径,True
print(os.path.isdir('D:/pytorch_learning'))   #是否是目录,True
print(os.path.isfile('D:/pytorch_learning'))  #是否是文件,False
print(os.path.exists('D:/pytorch_learning'))  #是否存在,True

print(os.path.getsize('b.txt'))   #字节大小,131
print(os.path.abspath('b.txt'))   #绝对路径,D:\pytorch_learning\python051_project\b.txt
print(os.path.dirname('D:/pytorch_learning'))   #返回目录的路径,D:/

print(os.path.getctime('b.txt'))   #创建的时间
print(os.path.getatime('b.txt'))   #最后访问的时间
print(os.path.getmtime('b.txt'))   #最后修改的时间

path = os.path.abspath('b.txt')
print(os.path.split(path))    #分割路径,返回一个元组,('D:\\pytorch_learning\\python051_project', 'b.txt')
print(os.path.splitext(path)) #返回文件拓展名,按点分割,('D:\\pytorch_learning\\python051_project\\b', '.txt')
print(os.path.join('d:\\','python','pytorch'))  #连接目录, d:\python\pytorch
# -*- coding: GBK -*-
#列出工作目录下所有的.py文件
import os
import os.path

work_dir = os.getcwd()
file_list = os.listdir(work_dir)  #获取所有子目录
for filename in file_list:
   if os.path.splitext(filename)[1] == '.py':#或if filename.endwith('py')
       print(filename)
print('##########')
file_list2 = [filename for filename in os.listdir(work_dir) if filename.endswith('txt')]#也可以用推导式
for f in file_list2:
    print(f,end='\n')
(4)walk()递归遍历所有文件和目录

在这里插入图片描述

# -*- coding: GBK -*-
import os
path = os.getcwd()
print(path)
file_list = os.walk(path)
for dirpath,dirnames,filenames in file_list:
    for dir in dirpath:
        print(dir)
(5)shutil拷贝
# -*- coding: GBK -*-
import shutil
shutil.copyfile('a.txt','a_copy.txt') #拷贝文件
shutil.copytree('movie','movie2')  #拷贝文件夹
shutil.copytree('movie','movie3',ignore=shutil.ignore_patterns('*.txt','*.zip')) #拷贝文件夹,.txt和.zip的都不考
(6)压缩

shutil.make_archive()
zipfile

# -*- coding: GBK -*-
import shutil
import zipfile
shutil.make_archive('movie/gg','zip','movie/Korae')#用shutil简单压缩
######用zipfile压缩########
z1 = zipfile.ZipFile('a.zip','w')
z1.write('a_copy.txt')
z1.write('a.copy.jpg')
z1.close()

z2 = zipfile.ZipFile('a.zip','r') #解压缩
z2.extractall('movie2')  #解压后放在movie2的目录下

3.递归算法

#阶乘
def factorial(i):

    global a
    a = a * i
    i = i-1
    if i >1:
        factorial(i)
    else:
        print(a)
######更简单的写法########
factorial(int(input('input one number:')))

def factorial2(i):
    if i == 1:
        return i
    else:
        return i*factorial2(i-1)

print(factorial2(5))
# -*- coding: GBK -*-
#递归打印所有目录和文件
import os
def getAllFiles(path):
    childFiles = os.listdir(path)
    for file in childFiles:
        filepath = os.path.join(path,file)
        if os.path.isdir(filepath):
            getAllFiles(filepath)
        print(filepath)
getAllFiles('movie')
'''结果
movie\a.txt
movie\America\bigbang
movie\America
movie\gg.zip
movie\Korae
'''
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值