[Python basics] day10-Python file operations (basic file operations, file backup, file and folder operations)

File operations

the goal

  • The role of file operations
  • Basic operation of files
    • turn on
    • Read and write
    • shut down
  • File backup
  • File and folder operations

1. The role of file operations

Thinking: What is a file?

Insert picture description here

Thinking: What does file operation include?

Answer: Open, close, read, write, copy...

Thinking: What is the role of file operations?

Answer: Read content, write content, backup content...

Summary: The role of file operations isStore some content (data), so that the program can be used directly when the program is executed next time, instead of making a new copy, saving time and effort

2. The basic operation of the file

2.1 File operation steps

  1. open a file
  2. Read and write operations
  3. Close file

Note: You can only open and close the file without any read or write operations.

2.1.1 Open

In python, using the open function, you can open an existing file, or create a new file, the syntax is as follows:

open(name, mode)

name: a 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.

2.1.1.1 Open file mode

mode description
r Open the file as read-only. The pointer of the file will be placed at the beginning of the file. This is the default mode.
rb Open a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode.
r+ Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
rb+ Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.
w Open a file for writing only. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wb Open a file in binary format for writing only. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
w+ Open a file for reading and writing. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wb+ Open a file in binary format for reading and writing. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
a Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
from Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
a+ Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. When the file is opened, it will be in append mode. If the file does not exist, create a new file for reading and writing.
from + Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.

2.1.1.2 Quick experience

f = open('test.txt', 'w')

Note: This fis openthe file object of the function.

2.1.2 File Object Method

2.1.2.1 Write
  • grammar
对象对象.write('内容')
  • Experience
# 1. 打开文件
f = open('test.txt', 'w')

# 2.文件写入
f.write('hello world')

# 3. 关闭文件
f.close()

note:

  1. wSum amode: If the file does not exist, create the file; if the file exists, the wmode is cleared and then written, and the amode is directly appended to the end.
  2. rMode: Report an error if the file does not exist.
2.1.2.2 Read
  • read()
文件对象.read(num)

num represents 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.

  • readlines()

readlines can read the contents of the entire file at one time in a row, and return a list, where each row of data is an element.

f = open('test.txt')
content = f.readlines()

# ['hello world\n', 'abcdefg\n', 'aaa\n', 'bbb\n', 'ccc']
print(content)

# 关闭文件
f.close()
  • readline()

readline() reads the content one line at a time.

f = open('test.txt')

content = f.readline()
print(f'第一行:{content}')

content = f.readline()
print(f'第二行:{content}')

# 关闭文件
f.close()

Insert picture description here

2.1.2.3 seek()

Role: used to move the file pointer.

The syntax is as follows:

文件对象.seek(偏移量, 起始位置)

starting point:

  • 0: beginning of file
  • 1: current location
  • 2: End of file

2.1.3 Close

文件对象.close()

3. File backup

Requirement: The user enters any file name in the current directory, and the program completes the backup function of the file (the backup file name is xx[backup] suffix, for example: test[backup].txt).

3.1 Step

  1. Receive the file name entered by the user
  2. Plan backup file name
  3. Backup file write data

3.2 Code implementation

  1. Receive user input target file name
old_name = input('请输入您要备份的文件名:')
  1. Plan backup file name

    2.1 Extract target file suffix

    2.2 The file name of the organization backup, xx [backup] suffix

# 2.1 提取文件后缀点的下标
index = old_name.rfind('.')

# print(index)  # 后缀中.的下标

# print(old_name[:index])  # 源文件名(无后缀)

# 2.2 组织新文件名 旧文件名 + [备份] + 后缀
new_name = old_name[:index] + '[备份]' + old_name[index:]

# 打印新文件名(带后缀)
# print(new_name)
  1. Backup file write data

    3.1 Open source file and backup file

    3.2 Write the source file data to the backup file

    3.3 Close the file

# 3.1 打开文件
old_f = open(old_name, 'rb')
new_f = open(new_name, 'wb')

# 3.2 将源文件数据写入备份文件
while True:
    con = old_f.read(1024)
    if len(con) == 0:
        break
    new_f.write(con)

# 3.3 关闭文件
old_f.close()
new_f.close()

3.3 Thinking

If the user inputs .txt, this is an invalid file, how can the program be changed to restrict only valid file names to be backed up?

Answer: Just add condition judgment.

old_name = input('请输入您要备份的文件名:')

index = old_name.rfind('.')


if index > 0:
    postfix = old_name[index:]

new_name = old_name[:index] + '[备份]' + postfix

old_f = open(old_name, 'rb')
new_f = open(new_name, 'wb')

while True:
    con = old_f.read(1024)
    if len(con) == 0:
        break
    new_f.write(con)

old_f.close()
new_f.close()

4. File and folder operations

The operation of files and folders in Python requires the use of related functions in the os module. The specific steps are as follows:

  1. Import the os module
import os
  1. Use osmodule related functions
os.函数名()

4.1 File Rename

os.rename(目标文件名, 新文件名)

4.2 Delete files

os.remove(目标文件名)

4.3 Create a folder

os.mkdir(文件夹名字)

4.4 Delete folder

os.rmdir(文件夹名字)

4.5 Get the current directory

os.getcwd()

4.6 Change the default directory

os.chdir(目录)

4.7 Get directory listing

os.listdir(目录)

5. Application cases

Requirement: To modify file names in batches, you can either add or delete the specified character string.

  • step
  1. Set the logo for adding and deleting strings
  2. Get all files in the specified directory
  3. Add/delete the specified string to the original file name to construct a new name
  4. os.rename() rename
  • Code
import os

# 设置重命名标识:如果为1则添加指定字符,flag取值为2则删除指定字符
flag = 1

# 获取指定目录
dir_name = './'

# 获取指定目录的文件列表
file_list = os.listdir(dir_name)
# print(file_list)


# 遍历文件列表内的文件
for name in file_list:

    # 添加指定字符
    if flag == 1:
        new_name = 'Python-' + name
    # 删除指定字符
    elif flag == 2:
        num = len('Python-')
        new_name = name[num:]

    # 打印新文件名,测试程序正确性
    print(new_name)
    
    # 重命名
    os.rename(dir_name+name, dir_name+new_name)

Six. Summary

  • File operation steps

    • turn on
    文件对象 = open(目标文件, 访问模式)
    
    • operating

      • read
      文件对象.read()
      文件对象.readlines()
      文件对象.readline()
      
      • write
      文件对象.write()
      
      • seek()
    • shut down

    文件对象.close()
    
  • Main access mode

    • w: write, create a new file if the file does not exist
    • r: read, report an error if the file does not exist
    • a: Append
  • File and folder operations

    • Rename: os.rename()
    • Get the current directory: os.getcwd()
    • Get the directory list: os.listdir()

Guess you like

Origin blog.csdn.net/qq_38454176/article/details/112230880