Python -- file operation

abstract

  • Role of file operation
  • Basic operation of files
    • open
    • Reading and writing
    • close
  • File backup
  • Operation of files and folders

1, Role of file operation

Thinking: what is a document?

Think: what does a file operation contain?

Answer: open, close, read, write, copy

Thinking: what is the role of file operation?

Answer: read content, write content, backup content

Summary: the function of file operation is to store some contents (data), which can be used directly the next time the program is executed without having to make a new copy, saving time and effort.

2, Basic operation of files

2.1 document operation steps

  1. Open file
  2. Read and write operations
  3. Close file

Note: you can only open and close files without any read-write operations.

2.1.1 opening

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

open(name, mode)

Name: is the string of the name of the target file to be opened (which can contain the specific path where the file is located).

Mode: set the mode of opening files (access mode): read-only, write, append, etc.

2.1.1.1 open file mode

patterndescribe
rOpen the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
rbOpen 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.
wOpen a file for writing only. If the file already exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wbOpen a file in binary format for writing only. If the file already exists, open the file and edit it 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 edit it 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 edit it from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
aOpen a file for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
abOpen a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. That is, 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. The file is opened in append mode. If the file does not exist, create a new file for reading and writing.
ab+Open a file in binary format for append. 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: f in this case is the file object of the open function.

2.1.2 document object method

2.1.2.1 write
  • grammar
Object object.write('content')
  • experience
# 1. Open the file
f = open('test.txt', 'w')

# 2. File writing
f.write('hello world')

# 3. Close the file
f.close()

be careful:

  1. W and a modes: if the file does not exist, the file is created; If the file exists, the w mode is cleared before writing, and the a mode is appended directly to the end.
  2. r mode: if the file does not exist, an error is reported.
2.1.2.2 reading
  • read()
File object.read(num)

Num indicates the length of the data to be read from the file (in bytes). If num is not passed in, it means that all the data in the file is read.

  • readlines()

readlines can read the contents of the whole file at one time in the form of lines, and return a list, in which the data of each line is an element.

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

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

# Close file
f.close()
  • readline()

readline() reads one line at a time.

f = open('test.txt')

content = f.readline()
print(f'First line:{content}')

content = f.readline()
print(f'Second line:{content}')

# Close file
f.close()

'''
first line:hello world
 Second line:abcdefg

'''
2.1.2.3 seek()

Function: used to move the file pointer.

The syntax is as follows:

File object.seek(Offset, Starting position)

Starting position:

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

2.1.3 closing

File object.close()

3, File backup

Requirement: the user inputs 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 steps

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

3.2 code implementation

  1. Receive user input destination file name
old_name = input('Please enter the file name you want to back up:')
  1. Planning backup file name

    2.1 extracting suffix of target file

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

# 2.1 extract the subscript of the suffix point of the file
index = old_name.rfind('.')

# print(index)  # 7  #Subscript in suffix

# print(old_name[:index])  	# new.txt		# Source file name (no suffix)

# 2.2 organization new file name old file name + [backup] + suffix
new_name = old_name[:index] + '[backups]' + old_name[index:]

# Print new file name (with suffix)
print(new_name)
# new.txt [backup]. mp3
  1. Backup file write data

    3.1 open source and backup files

    3.2 write source file data to backup file

    3.3 closing documents

# 3.1 opening files
old_f = open(old_name, 'rb')
new_f = open(new_name, 'wb')

# 3.2 write source file data to backup file
while True:
    con = old_f.read(1024)
    if len(con) == 0:
        break
    new_f.write(con)

# 3.3 closing documents
old_f.close()
new_f.close()

3.3 thinking

If the user enters. txt, which is an invalid file, how can the program change to limit that only valid file names can be backed up?

A: add condition judgment.

old_name = input('Please enter the file name you want to back up:')

index = old_name.rfind('.')


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

new_name = old_name[:index] + '[backups]' + 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, Operation of files and folders

In Python, the operation of files and folders depends on the relevant functions in the os module. The specific steps are as follows:

  1. Import os module
import os
  1. Using os module related functions
os.Function name()

4.1 file renaming

os.rename(Destination file name, New file name)

4.2 deleting files

os.remove(Destination file name)

4.3 creating folders

os.mkdir(Folder name)

4.4 delete folder

os.rmdir(Folder name)

4.5 get current directory

os.getcwd()

4.6 changing the default directory

os.chdir(catalogue)

4.7 get directory list

os.listdir(catalogue)

5, Application case

Requirement: modify the file name in batch. You can add and delete the specified string.

  • step
  1. Sets the identity of the string to be added or deleted
  2. Gets all files in the specified directory
  3. Add / delete the specified string of the original file name to construct a new name
  4. os.rename() rename
  • code
import os

# Set rename ID: if it is 1, the specified character will be added; if flag is 2, the specified character will be deleted
flag = 1

# Gets the specified directory
dir_name = './'

# Gets the list of files in the specified directory
file_list = os.listdir(dir_name)
# print(file_list)


# Traverse the files in the file list
for name in file_list:

    # Add specified character
    if flag == 1:
        new_name = 'Python-' + name
    # Delete specified character
    elif flag == 2:
        num = len('Python-')
        new_name = name[num:]

    # Print the new file name to test the correctness of the program
    print(new_name)
    
    # rename
    os.rename(dir_name+name, dir_name+new_name)

6, Summary

  • File operation steps

    • open
    File object = open(Target file, Access mode)
    
    • operation

      • read
      File object.read()
      File object.readlines()
      File object.readline()
      
      • write
      File object.write()
      
      • seek()
    • close

    File object.close()
    
  • Primary access mode

    • w: Write. If the file does not exist, create a new file
    • r: If the file does not exist, an error will be reported
    • a: Add
  • File and folder operations

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

Tags: Python Pycharm

Posted on Sat, 20 Nov 2021 12:20:00 -0500 by _theworks