Python Basics 08-Detailed Explanation of File Operations

Zero, article directory

Python Basics 08-Detailed Explanation of File Operations

1. Overview of file operations

(1) What is a file
  • The data stored in the memory will disappear after the computer is shut down. To save data for a long time, you need to use hard disks, optical disks, USB disks and other devices. In order to facilitate data management and retrieval, the concept of "file" is introduced.

  • 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. Generally speaking, == files can be divided into various categories such as text files, video files, audio files, image files, and executable files.

image-20231120154443232

(2) What operations are performed on files?
  • In daily life, file operations mainly include operations such as opening, closing, reading, writing, and backup.
(3) The role of file operations
  • The function of file operation is to store some content (data) so that it can be used directly the next time the program is executed without having to make a new copy, saving time and effort.
  • To put it simply, it is to achieve the persistence of data!

2. Basic operations of files

(1) File operation steps
  • ① Open the file
  • ② Read and write files
  • ③ Close the file
(2) open() opens the function
  • In Python, you can use the open function to open an existing file or create a new file. Syntax: open(name, mode)

    • name: is a string of the name of the target file to be opened (can include the specific path where the file is located).
    • mode: Set the mode (access mode) for opening the file: read-only, write, append, etc.
  • File path: ① Absolute path ② Relative path

    • ① Absolute path: Absolute path represents an absolute concept. It usually starts from the drive letter, and then searches downward one level at a time (no skipping levels) until the file we want to access is found.
    • ② Relative path: Relative path represents a relative concept. There is no need to start from the drive letter. First, you need to find a reference point (which is the Python file itself)
      • Sibling relationship: The file we want to access is in the same directory as the Python code. It is a parallel relationship. To access the sibling relationship, you can use ./文件名称 or write directly 文件名称That’s it
      • Superior relationship: If the file we want to access is in the upper-level directory of the current Python code, we can access the upper-level path through ../ (if it is multi-level, also You can access it layer by layer through.../…/…/
      • Subordinate relationship: If the file we want to access is in a folder at the same level as the Python code, we can access the file in a certain directory through文件夹名称/ a>
(3) Detailed explanation of mode access mode

image-20231120162401489

(4) Quick start of writing operation
'''
文件操作三步走:① 打开文件 ② 读写文件 ③ 关闭文件
① 打开文件 => open(name, mode)
name = 代表要打开的文件路径 + 名称
mode代表访问模式,只需要记住三种模式即可 => r/w/a
r : read,只读模式,代表只能对文件进行读取,属于默认模式,如果要访问的文件不存在,则直接报错!
w : write,只写模式,代表只能对文件进行写入操作,如果访问的文件不存在,则系统会自动创建,但是写入文件时,
它首先要把文件内容清空,然后再写入新内容。
a : append,追加模式(只写模式的一种),与w类似,如果访问的文件不存在,也可以自动创建该文件。
但是在写入数据到文件时,其并不会清空文件的原有内容。
注意:open方法操作完成后,返回的是一个文件对象(对象的概念后面会学,也可以叫做文件句柄)
以后的读写都需要依赖这个对象(句柄)
② 写内容到文件 => f.write(content) => f.write()只能把字符串类型的数据写入到文件中
③ 关闭文件(为什么要关闭文件 => 因为文件打开以后需要占用计算机资源)
f.close()
'''
# 1、打开文件
f = open('python.txt', 'w')
# 2、写入内容到文件
f.write('Life is Short, I Study Python!')
# 3、关闭文件
f.close()
(4) Solve the problem of writing garbled Chinese characters
  • Specifying the character set encoding='utf-8' when opening allows the program to read and write according to the specified character set.
'''
乱码是如何产生的?把这个原因说清楚!
大多数编程语言都是老外开发的,对中文的支持并不好。最早美国搞出了一套编码格式 => ASCII => 1字节 => 8bit
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
2的8次方 => 主要能表达255个字符(主要包括了0-9,a-z,A-Z,老外字符)
随着编程语言和互联网发展,语言传入国内了,发现255个字符根本装不了汉字。所以就会产生所谓的乱码!
中国推出了自己的编码格式 => GB2312 => 比较广,传统255个字符 + 汉字支持 => GBK
中国台湾 => 喜欢使用繁体中文 => Big5
国际化组织受不了,每开一个系统,兼容所有语言 => 开发好几套系统 => 编码标准unicode => UTF-8
'''
# 1、打开文件
f = open('python.txt', 'w', encoding='utf-8')
# 2、写入内容到文件
f.write('人生苦短,我学Python!')
# 3、关闭文件
f.close()
(5) Read operation related methods
  • read(): Read all the contents of the file. You can add a parameter size, which represents the length of characters to be read. If num is not passed in, it means reading all the data in the file.
  • readlines(): Read all the contents of the file at once. The return result is a list. Each element in the list is a line in the file.
  • readline(): Read one line of the file at a time, and move backward once read, until the file is read. It is rarely used by itself. It is usually used in conjunction with while
'''
文件读取也要分为三步走:
① 打开文件 f = open()
② 读取文件
③ 关闭文件 f.close()
在Python代码中,文件读取一共有3种方法:
read() : 读取文件的所有内容,可以添加一个参数size,代表读取字符长度
readlines() : 一次性读取文件的所有内容,返回结果是一个列表,列表中的每一个元素都是文件中的一行
readline() : 一次读取文件的一行,读取一次向后移动一次,直到文件读取完毕,很少自己使用,通常要配合while True
'''
# 1、第一种方法
# f = open('python.txt', 'r', encoding='utf-8')
# # content = f.read()  # 读取文件所有内容
# content = f.read(1)   # 代表只读取文件中的一个字符
# print(content)
# f.close()

# 2、第二种写法
# f = open('python.txt', 'r', encoding='utf-8')
# content = f.readlines()
# print(content)
# f.close()

# 3、第三种写法
f = open('python.txt', 'r', encoding='utf-8')
while True:
    content = f.readline()
    # 判断,如果读取不到任何内容,则结束循环
    if not content:
        break
    # 反之,如果没有执行break,则代表文件中还有内容
    print(content, end='')

print(content)
f.close()
(6) File backup case
  • Requirement: The user enters any file name in the current directory to complete the backup function of the file (the backup file name is xx [backup] suffix, for example: test [backup].txt).
'''
需求:用户输入当前目录下任意文件名,完成对该文件的备份功能(备份文件名为xx[备份]后缀,例如:(test[备份].txt)。
① 命名变化:test.txt => 备份 => test[备份].txt
② 内容变化:需要把旧文件中的内容完全拷贝到新文件中
分析:命名变化如何实现
test.txt => test[备份].txt?
☆ 提示用户输入要备份的文件名称
☆ 分别获取文件的名称以及文件的后缀 => (文件名 => test 后缀 => .txt)
☆ 重新拼接新文件 test + [备份] + .txt
新方法:rfind()方法,从左向右查找,返回这个关键词在最后一次出现的位置
test.abc.txt

分析:文件内容变化
旧文件 => 读取操作
新文件 => 写入操作
把旧文件的内容全部读取出来写入到新文件中,但是文件如果比较大,考虑使用read或readline
'''
oldname = input('请输入您要备份的文件名称:')
# oldname = 'test.txt',拆解文件名与文件的后缀
index = oldname.rfind('.')
# 获取文件名称
filename = oldname[:index]  # test
postfix = oldname[index:]   # .txt
# 拼接新文件名称
newname = filename + '[备份]' + postfix

# 创建old_f文件句柄与new_f文件句柄
old_f = open(oldname, 'rb')
new_f = open(newname, 'wb')
while True:
    content = old_f.read(1024)  # r模式size代表字符长度,rb模式size代表字节大小 => 1KB
    if not content:
        break
    new_f.write(content)
# 操作完成后,关闭文件
old_f.close()
new_f.close()

3. File and folder operations

(1)os module
  • To operate files and folders in Python, you need to use the relevant functions in the os module. The specific steps are as follows:
  • ① Import os module
import os
  • ② Also use related functions of the os module
os.函数()
(2) Methods related to file operations
  • os.rename (old file name, new file name): Rename the file
  • os.remove (name of file to be deleted): delete the file
'''
os.rename(旧文件名称, 新文件名称)
os.remove('要删除的文件名称')

案例:把Python项目目录下的python.txt文件,更名为linux.txt,查看效果后,对文件进行删除操作。
'''
# 1、导入os模块
import os

# 2、对python.txt重命名为linux.txt
if os.path.exists('python.txt'):
    os.rename('python.txt', 'linux.txt')

# 3、把linux.txt移除
os.remove('linux.txt')
(3) Methods related to folder operations
  • os.mkdir (new folder name): Create a folder with the specified name
  • os.getcwd(): current work directory, get the current directory name
  • os.chdir (name of directory after switch): change directory, switch directory
  • os.listdir (target directory): Get file information in the specified directory and return the list
  • os.rmdir (target directory): used to delete an "empty" folder with a specified name
'''
import os模块

os.mkdir() 创建一个文件夹
os.getcwd() 获取当前程序工作目录
os.chdir()  =>  change directory,切换目录
os.listdir() => list directory,以列表形式展现一个目录下的所有文件信息
os.rmdir()  =>  remove directory,移除目录(删除文件夹,缺点:只能删除空文件夹)

案例:准备一个static文件夹以及file1.txt、file2.txt、file3.txt三个文件
① 在程序中,将当前目录切换到static文件夹
② 创建一个新images文件夹以及test文件夹
③ 获取目录下的所有文件
④ 移除test文件夹
'''
import os

# 1、我目前在什么位置
print(os.getcwd())
# 2、把当前工作目录切换到static文件夹
os.chdir('static')
# 3、创建images与test文件夹
if not os.path.exists('images'):
    os.mkdir('images')
if not os.path.exists('test'):
    os.mkdir('test')
# 4、获取一个目录下的所有文件
files = os.listdir()
print(files)
# 5、删除目录
if os.path.exists('test'):
    os.rmdir('test')
(4) Recursively delete non-empty directories (be careful)
'''
Ctrl + 鼠标左键点击一下模块,可以打开模块底层代码
'''
import shutil

shutil.rmtree('static')

Guess you like

Origin blog.csdn.net/liyou123456789/article/details/135039314