Python之open()/OS,打开文件进行读取,如


1.File对象数据读写与操作

#def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
#file: 操作的文件
#mode:打开这个文件的模式
    'r'       open for reading (default)读取 - 默认值。打开文件进行读取,如果文件不存在则报错。
    'w'      open for writing, truncating the file first写入 - 打开文件进行写入,如果文件不存在则创建该文件。
    'x'       create a new file and open it for writing创建 - 创建指定的文件,如果文件存在则返回错误。
    'a'       open for writing, appending to the end of the file if it exists追加 - 打开供追加的文件,如果不存在则创建该文件。
    'b'       binary mode二进制模式
    't'       text mode (default)文本 - 默认值。文本模式。
    '+'       open a disk file for updating (reading and writing)打开磁盘文件进行更新(读写)
    'U'       universal newline mode (deprecated)通用换行模式(已弃用)
#buffering:可选参数,用于指定对文件做读写操作时,是否使用缓冲区
#encoding:手动设定打开文件时所使用的编码格式,不同平台的 ecoding 参数值也不同,以 Windows 为例,其默认为 cp936(实际上就是 GBK 编码)

2.读取

file = open("test0925.py")#默认为r
res = file.read()
print(res)
#def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
#file: 操作的文件
#mode:打开这个文件的模式
file = open("test0925.py","r")#默认为r
res = file.read()
print(res)

3.写入

#写入
file = open("test0925.py","w",encoding="utf8")#w写入,覆盖源文档的内容,乱码时添加encoding="utf8"
file.write("测试")

4.追加

#追加
file = open("test0925.py","a",encoding="utf8")#w写入,覆盖源文档的内容,乱码时添加encoding="utf8"
file.write("aaaa")

5.按行读取

#按行读取
file = open("test0925.py","r",encoding="utf8")
read = file.readline()#读取一行
print(read)

6.读取多行

#全部读取
file = open("test0925.py","r",encoding="utf8")
reads = file.readlines()#读取所有行
print(reads)

7.OS操作文件夹

文文件夹(目录)

7.1.绝对路径/相对路径

#相对路径/绝对路径
第一种(绝对路径表示法):C:\FIle\file two
第二种(相对路径表示法):FIle two

7.2.新建目录

import os
#新建文件夹
os.mkdir("Eclipse")#

7.3.跨级新建目录

import os
#跨级新建目录
os.mkdir("Eclipse/US")#跨级必须确保层级目录存在,相对路径

7.4.绝对路径新建目录

import os
#绝对路径新建目录
os.mkdir("D:\\test_mkdir")#绝对路径

7.5.删除目录

#目录不为空时删除失败

import os
#删除文件夹
os.remove("demo.py")
import os
#删除
os.rmdir("m1/m2")

8.OS获取路径

8.1.获取当前工作目录

#获取当前工作目录
import os
path = os.getcwd()
print(path)#D:\File\python_project\demo\api

2.2.获取当前文件所在的绝对路径(具体到模块名)

#获取当前文件所在的绝对路径
import os
realpath = os.path.realpath(__file__)# __file__表示当前文件本身
print(realpath)#D:\File\python_project\demo\api\demo02.py

2.3.拼接路径 +

#拼接路径
import os
new_path = os.getcwd()+"\\m1\\m2" # \\两个反斜杠可以,\一个反斜杠可以,/一个斜杠也可以
print(new_path) #打印新的绝对路径

 2.4.拼接路径 join

#路径拼接
import os
path = os.getcwd().join("test02") #拼接
print(path)
file = os.path.join("C/itt","ABC")#☆ ☆
print(file) #C/itt\ABC

2.5.判断是否为文件

#判断文件
import os
path = os.path.isfile(__file__)#判断是否为文件
print(path)#True

path2 = os.path.isfile(os.getcwd())#判断当前路径是否为文件
print(path2)#False

2.6.判断是否为文件夹

#判断文件夹
import os
path = os.path.isdir(__file__)#判断当前绝对路径是否为文件夹
print(path)#False

path2 = os.path.isdir(os.getcwd())
print(path2)#True

2.7.判断路径是否存在

#判断路径是否存在
import os
bool = os.path.exists("D://download")
print(bool) #True

2.8.打印指定路径下所有文件和文件夹

#罗列当前路径下所有的文件文件夹
import os
list_path = os.listdir("C:\system_software\PyCharm 2019.1.3")
print(list_path)#['bin', 'build.txt', 'debug-eggs', 'help', 'helpers', 'helpers-pro', 'index', 'jre64', 'lib', 'license', 'plugins', 'product-info.json', 'skeletons']

2.9.写一个函数,判断是否为目录,如果时目录罗列出所有的文件文件夹

#写一个函数,判断是否为目录,如果时目录罗列出所有的文件文件夹
import os
def path_list(path):
    if os.path.exists(path) and os.path.isdir(path):#判断是否为文件夹,是否存在
        for item in (os.listdir(path)):#便利列表
            new_path = path + "\\" + item   #使用join拼接: new_path = os.path.join(path,item)                                      
            if os.path.isdir(new_path):#是否为文件夹
                print("D:{0}".format(new_path))#文件夹
            elif os.path.isfile(new_path):#是否为文件
                print("F:{0}".format(new_path))#文件
            else:
                print("错误路径:{0}".format(new_path))
path_list("C:\system_software\PyCharm 2019.1.3")

输出:
    D:C:\system_software\PyCharm 2019.1.3\bin
    F:C:\system_software\PyCharm 2019.1.3\build.txt
    D:C:\system_software\PyCharm 2019.1.3\debug-eggs
    D:C:\system_software\PyCharm 2019.1.3\help
    D:C:\system_software\PyCharm 2019.1.3\helpers
    D:C:\system_software\PyCharm 2019.1.3\helpers-pro
    D:C:\system_software\PyCharm 2019.1.3\index
    D:C:\system_software\PyCharm 2019.1.3\jre64
    D:C:\system_software\PyCharm 2019.1.3\lib
    D:C:\system_software\PyCharm 2019.1.3\license
    D:C:\system_software\PyCharm 2019.1.3\plugins
    F:C:\system_software\PyCharm 2019.1.3\product-info.json
    D:C:\system_software\PyCharm 2019.1.3\skeletons

3.拓展(递归)

通过递归 获取指定路径下所有的文件文件夹,包括文件夹下的所有文件和文件夹
#通过递归 获取指定路径下所有的文件文件夹,包括文件夹下的所有文件和文件夹
import os
def aqual_path(path):
    # os.path.exists(path)#判断是否为路径
    # os.path.isdir(path)#是否为一个文件夹
    if os.path.exists(path) and os.path.isdir(path):
        #若果是一个有效的文件夹,则获取当前路径下所有文件/文件夹
        listss = os.listdir(path)
        for item in listss:
            new_path = os.path.join(path,item)
            if os.path.isdir(new_path):
                print("D:{0}".format(new_path))
                aqual_path(new_path)#递归,调用本函数
            elif os.path.isfile(new_path):
                print("F:{0}".format(new_path))
            else:
                print("无效:{0}".format(new_path))

aqual_path("E:\娱乐\电影集\China")

输出:
D:E:\娱乐\电影集\China\林超贤导演
F:E:\娱乐\电影集\China\林超贤导演\红&海&行动.mp4
F:E:\娱乐\电影集\China\真三国无shuang.2021.HD.1080P.国粤双语中字.mkv
F:E:\娱乐\电影集\China\误杀2.2021.HD.1080P.国语中英双字.mkv
F:E:\娱乐\电影集\China\送你一朵小红hua.mkv
D:E:\娱乐\电影集\China\郭敬明导演
F:E:\娱乐\电影集\China\郭敬明导演\爵1迹1.mp4
F:E:\娱乐\电影集\China\郭敬明导演\爵1迹2:冷血狂宴.mp4
F:E:\娱乐\电影集\China\长津湖.2021.BD.1080P.国语中字.mkv

 

相关内容

    暂无相关文章

评论关闭