Python中open()文件操作/OS目录操作

  • 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 编码)

1.读取

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)

2.写入

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

3.追加

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

4.按行读取

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

5.读取多行

#全部读取
file = open("test0925.py","r",encoding="utf8")
reads = file.readlines()#读取所有行
print(reads)
  • OS对目录的操作以及引用

绝对路径/相对路径

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

新建目录

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

跨级新建目录

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

绝对路径新建目录

import os
#绝对路径新建目录
os.mkdir("D:\\test_mkdir")#绝对路径
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。