首页 > 编程语言 >Python中open()文件操作/OS目录操作

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

时间:2022-12-17 18:12:01浏览次数:47  
标签:文件 None 读取 encoding Python open file 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")#绝对路径

 

标签:文件,None,读取,encoding,Python,open,file,OS
From: https://www.cnblogs.com/QAbujiaban/p/16989301.html

相关文章