Python file and directory operations

Table of contents

file encoding

file reading

open a file

The three basic access modes commonly used in mode

read file

close file

with open syntax

file write operation

Comprehensive case of documents

a.txt content

Code

b.txt file

directory operations

foreword

os module

specific method 

os.path module

specific method 

file encoding

Preface: Since computers can only recognize 0 and 1, our rich text files are stored in

Coding technology: the rules of translation, which record how to translate content into binary and how to translate binary into recognizable content

Note: There are many encodings available in the computer (UTF-8, GBK, Big5), etc. Different encodings translate the contents into different binary formats, so the correct encoding must be used to read and write files correctly.

file reading

Preface: The data stored in the internal memory will disappear after the computer is turned off. If you want to save the data for a long time, you need to use hard disk, CD, U disk and other devices. In order to facilitate data management and retrieval, the concept of files is introduced

Notice:

  • An article, a video, and an executable program can all be saved as a file and given a file name
  • The operating system manages data on the disk in units of files.
  • Files can be divided into text files, video files, audio files, image files, executable files, etc.
  • In daily life, file operations mainly include opening, closing, reading, writing, etc.

open a file

Syntax: file object=open(name,mode,encoding=encoding format)

parameter explanation 

  • name: the string of the target file name to be opened (can include the specific path where the file is located)
  • mode: Set the mode of opening the file (access mode): read-only, write, append, etc.
  • Encoding format: file encoding format (UTF-8 is recommended)

Notice:

  • The three parameters passed in are all in string format 
  • Because encoding is not the third parameter, parameters cannot be passed in order

The three basic access modes commonly used in mode

read file

Syntax: variable = file object.read(num)

Explanation: num indicates the length of the data to be read from the file (in bytes), if num is not passed in, it means to read all the data in the file

Syntax: variable = file object.readlines()

Explanation: readlines can read the contents of the entire file at one time by line, and return a list in which each line of data is an element

Syntax: variable = file object.readline()

Explanation: Read one line at a time

for loop to read lines from file

for line in 文件对象:
    print(line)

Understanding: Each line temporary variable records a line of data in the file 

Note: When we read a file, as long as the file object is opened, no matter what file reading method is called later, it will continue the last method of reading the file.

close file

Syntax: file object.close()

Note: If you do not call close and the program does not stop running, then this file will always be occupied by the python program

with open syntax

with open(name,mode,encoding) as 文件对象变量:
    f.readlines()

Note: By operating the file through the with open statement block, the close file can be automatically closed after the operation is completed, so as to avoid forgetting the close method

file write operation

Write a file to memory: file object.write (written content)

File flush: file object.flush()

Notice

  • When using the open function to write a file in w mode, the file will be created if the file does not exist, and the original file content will be overwritten if the file exists; if the file does not exist in a mode, the file will be created, and the file will be added on the basis of the source file if the file exists content
  • Here, the file appending of the a parameter can also be added after closing the file. If the file is not closed, the w parameter call write file is always in the append mode
  • Call write directly, the content is not actually written into the file, but will be accumulated in the memory of the program, called the buffer
  • When flush/close is called, the content will actually be written to the hard disk
  • The purpose of this is to avoid frequent operation of the hard disk, resulting in a decrease in efficiency (save a pile, write to the hard disk at one time)

Comprehensive case of documents

Requirement: Back up the contents of the a.txt file to the b.txt file

a.txt content

Code

#打开a.txt文件
fr=open("D:/test/a.txt","r",encoding="UTF-8")
#打开b.txt文件,准备写入
fw=open("D:/test/b.txt","w",encoding="UTF-8")
#读取a.txt文件的所有数据
for line in fr:
    #将每次读取的数据写入b.txt
    fw.write(line)
#将内存中的数据刷新至硬盘
fw.flush()
#关流
fw.close()
fr.close()

b.txt file

directory operations

foreword

  • The os module is a built-in python module related to operating system functions and file systems. The execution results of the statements in this module are usually related to the operating system. Running on different operating systems, the results obtained may be different
  • The os module and the os.path module are used to operate on directories or files, which is a module that comes with the python system

os module

Before use: import os

specific method 

import os
#执行命令行语句
os.system("python -V")
#直接启动文件
os.startfile("D:/test/a.txt")
#返回指定路径下的文件和目录信息
print(f"文件和目录信息:{os.listdir('D:/app/youdao')}")
#创建目录
os.mkdir("D:/test/dir1")
#创建多级目录
os.makedirs("D:/test/dir2/dir3")
#删除目录
os.rmdir("D:/test/dir1")
#删除多级目录
os.removedirs("D:/test/dir2/dir3")
#设置当前工作目录
os.chdir("D:/test")
#当前的工作目录
print(f"当前的工作目录为{os.getcwd()}")

os.path module

Before use: import os.path

specific method 

import os.path
#获取当前位置的绝对路径(end.py为当前位置的文件)
print(os.path.abspath("end.py"))
#判断当前文件夹下的文件或目录是否存在
print(os.path.exists("end.py"))
#将目录与目录或目录与文件名拼接
print(os.path.join("D\python", "app.txt"))#D\python\app.txt
#分离路径和文件名
print(os.path.split("D:\projects\end.py"))#('D:\\projects', 'end.py')
#分离文件名和扩展名
print(os.path.splitext("app.py"))#('app', '.py')
#从一个目录中提取文件名
print(os.path.basename("D:\projects\end.py"))#end.py
#从一个目录中提取目录不包括文件名
print(os.path.dirname("D:\projects\end.py"))#D:\projects
#判断是否为目录(有end.py不是)
print(os.path.isdir("D:\projects\end.py"))#False

Guess you like

Origin blog.csdn.net/m0_60027772/article/details/132120405