python之文件读写、目录操作、序列化str操作后写入文档

一、文件打开

open函数是用来打开文件;格式:open (name[.mode[.buffering]]);

必填参数

1.name(即:文件名或文件路径);

选填参数

1.mode(即:权限模式)、包含:w、r、b、a、+;

2.buffering(即:控制文件的缓冲),如值为0,无缓冲,直接将数据写到硬盘;若为1,有缓冲,在flush()或close()执行后

数据才会更新到硬盘;如为大于1的数字则代表缓冲区大小(字节);如为负数,表示默认缓冲区的大小;

mode值 功能描述
r 读模式
w 写模式
a 追加模式
b 二进制模式(可添加到其他模式中使用)
+ 读/写模式(可添加到其他模式中使用)
f=open(r'c:\study\test.txt','r')#默认也是r模式
如果文件不存在,会报错;

二、文件读取

read()、readline()、readlines()的区别:

由于在文件打开后,都有执行close()方法;但是如果IO异常,close()方法就不会执行;为了代码的健壮性,有两种方式:

1.try……finally……:无论如何都要执行finally后面的代码块;

2.with open(r'xxx.txt','r') as f;

try:
    f = open("../stu001.txt", 'r+')
    print(f.read())
finally:
    if f:
        f.close()
########################################################
with open(r'../stu001.txt','r+') as f:
    print(f.read())
###由于很多文件数据较大,如:配置文件等,readlines()方法更加合理####
with open(r'../stu001.txt','r+') as f:
    for line in f.readlines():
        print(line.strip())

三、文件写入

n=['11111\n','222222\n','333333\n','44444\n','555']
with open(r'../stu001.txt','w') as f:
    for n1 in n:
        f.writelines(n1)

四、操作文件和目录

主要使用的包:os、shutil

# -*-coding:utf-8-*-

# f = open("../stu001.txt",'r+')
# print("-----111-------\n"+f.read())
# f.close()
# f = open("../stu001.txt",'r+')
# print("-----222-------\n"+f.readline())
# f.close()
# f = open("../stu001.txt",'r+')
# print("-----333-------")
# print(f.readlines())
# f.close()



# try:
#     f = open("../stu001.txt", 'r+')
#     print(f.read())
# finally:
#     if f:
#         f.close()
# ########################################################
# with open(r'../stu001.txt','r+') as f:
#     print(f.read())
# ###由于很多文件数据较大,如:配置文件等,readlines()方法更加合理####
# n=['11111\n','222222\n','333333\n','44444\n','555']
# with open(r'../stu001.txt','w') as f:
#     for n1 in n:
#         f.writelines(n1)

import os
'''获得当前python脚本工作的目录路径'''
print(os.getcwd())#   D:\pythonProject\study\study001\
'''获得当前python脚本工作的文件路径'''
print(__file__)#   D:/pythonProject/study/study001/001_file_opearation.py
'''返回指定目录下的所有文件及目录名,默认当前目录路径'''
print(os.listdir("D:\pythonProject\study\study001"))#   ['001_file_opearation.py', '__init__.py']
print(os.listdir())#   ['001_file_opearation.py', '__init__.py']
'''删除一个文件'''
os.remove(r"D:\pythonProject\study\study001\test")
'''删除多个空目录'''
os.removedirs(r"D:\pythonProject\study\study001\test\test001")
'''检验给出的路径是否是一个文件'''
os.path.isfile(r"D:\pythonProject\study\stu001.txt")
'''检验给出的路径是否是一个目录'''
os.path.isdir("D:\pythonProject\study\stu001.txt")
'''判断是否是绝对路径'''
os.path.isabs("D:\pythonProject\study\study001")
'''判断路径是否真的存在'''
os.path.exists("D:\pythonProject\study\study001")
'''分离一个路径的目录名和文件名'''#结果返回一个tuple
print(os.path.split("D:\pythonProject\study\stu001.txt"))#('D:\\pythonProject\\study', 'stu001.txt')
'''分离一个路径的扩展名'''#结果返回一个tuple
print(os.path.splitext("D:\pythonProject\study\stu001.txt"))#('D:\\pythonProject\\study\\stu001', '.txt')
'''获取路径名'''
print(os.path.dirname("D:\pythonProject\study\stu001.txt"))
'''获取文件名'''
print(os.path.basename("D:\pythonProject\study\stu001.txt"))
'''重命名文件或目录'''
os.rename(old,new)
'''创建多级目录'''
os.makedirs(r'D:\pythonProject\study\study001\te')
'''创建单个目录'''
os.mkdir("tes")
'''获取文件属性'''
os.stat("D:\pythonProject\study\stu001.txt")
'''获取文件大小'''
os.path.getsize("D:\pythonProject\study\stu001.txt")

import shutil
'''复制文件夹'''
shutil.copytree("olddir","newdir")#olddir、newdir都只能是目录,且mewdir必须不存在
'''复制文件'''
shutil.copyfile("oldfile","newfile")#oldfile、newfile都只能是文件
shutil.copy("oldfile","new")#oldfile只能是文件,new可以是文件,也可是目标目录
'''移动文件/目录'''
shutil.move('oldpos','newpos')
'''删除目录'''
os.rmdir('dir')#只能删除空目录
shutil.rmtree('dir')#空目录、有内容的目录都可删除

五、序列化(str)

(关联:json序列化:https://blog.csdn.net/ak739105231/article/details/83958344?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522158624592819726867828381%2522%252C%2522scm%2522%253A%252220140713.130056874..%2522%257D&request_id=158624592819726867828381&biz_id=0&utm_source=distribute.pc_search_result.none-task-blog-blog_SOOPENSEARCH-1)

python中提供两个模块:cPickle、pickle;前者是C语言编写的,效率比后者高很多;但是功能是一样的;

try:
    import cPickle as pickle
except ImportError:
    import pickle

pickle实现序列化主要是使用dump方法或dumps方法;dumps方法可以将任意对象序列化成一个str;然后将其写入文件;dump方法可以直接将序列化后的对象直接写入文件中;

n=['11111\n','222222\n','333333\n','44444\n','555']
######################方式一:############################
n_new=pickle.dumps(n)
with open('../stu001.txt','wb') as f:
    f.write(n_new)

######################方式二:############################

with open('../stu001.txt','wb') as f:
    pickle.dump(n,f)
发布了232 篇原创文章 · 获赞 141 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/ak739105231/article/details/105362615