"No action, no intention" Python foundation - 43. Implementation of file backup

Posted by rowantrimmer on Sat, 29 Jan 2022 02:20:30 +0100

Python wechat ordering applet course video

https://edu.csdn.net/course/detail/36074

Python actual combat quantitative transaction financial management system

https://edu.csdn.net/course/detail/35475
Catalogue* 1. Demand

1. Demand

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.

2. Steps

  1. Receive the file name entered by the user.
  2. Plan backup file name.
  3. Write data to the backup file.

3. Code implementation

(1) Receive user input target file name

python

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

(2) Planning backup file name

2.1 extract the suffix of the target file.
2.2 file name of organization backup, suffix xx [backup].

python

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

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

(3) Backup file write data

3.1 open source files and backup files.
3.2 write the source file data into the backup file.
3.3 close the file.

python

# 3.1 opening files
old\_f = open(old\_name, 'rb')
new\_f = open(new\_name, 'wb')

# 3.2 write source file data into backup file
# If you are not sure about the target file size, cycle reading and writing,
# When the read data is gone, the loop is terminated
while True:
    # Contents read in the original file each time
    con = old\_f.read(1024)
    # Indicates that the read is complete
    if len(con) == 0:
        # Terminate reading
        break

    # New file write read data
    new\_f.write(con)

# 3.3 closing documents
old\_f.close()
new\_f.close()

(4) Think

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

Answer: add condition judgment.

python

# The suffix can only be extracted if there is a file name
# Suffixes cannot be obtained here. Variables without suffixes are spliced
# Will report an error
if index > 0:
    postfix = old\_name[index:]

(5) Complete coding

1) Traditional implementation

python

# 1. The user inputs the target file, such as sound txt. mp3
old\_name = input('Please enter the file name you want to back up:')

# 2. Name of planning backup file
# 2.1 extracting suffixes--
# Find the rightmost point in the name is the suffix point
# Find the rfind() method on the right
# Gets the suffix in the full file name Location of
index = old\_name.rfind('.')


# 4. Thinking: only valid files can be backed up txt
if index > 0:
    # Extract the suffix. If it cannot be extracted here, an error will be reported when splicing the new file name later
    postfix = old\_name[index:]

# 2.2 organization new name = original name + [backup] + suffix
# The original name is a molecular string in the string -- slice [start: end: step]
# new\_name = old\_name[:index] + '[backup]' + old\_name[index:]
new\_name = old\_name[:index] + '[backups]' + postfix


# 3. Write data to the backup file (the data is the same as the original file)
# 3.1 open original and backup files
old\_f = open(old\_name, 'rb')
new\_f = open(new\_name, 'wb')

# 3.2 original file reading and backup file writing
# If the size of the target file is not determined, the cycle is read and written. When the read data is not available, the cycle is terminated
while True:
    # Contents read in the original file each time
    con = old\_f.read(1024)
    # Indicates that the read is complete
    if len(con) == 0:
        # Terminate reading
        break

    # New file write read data
    new\_f.write(con)

# 3.3 closing documents
old\_f.close()
new\_f.close()

2) Actual work realization

python

# 1. The user inputs the target file, such as sound txt. mp3
old\_name = input('Please enter the file name you want to back up:')

# Gets the suffix in the full file name Location of
index = old\_name.rfind('.')

# 4. Only valid files can be backed up txt
if index > 0:
    postfix = old\_name[index:]

# 3. Start backing up files
# Open original file
with open(old\_name , 'rb') as file\_obj:
    # New organization name = original name + [backup] + suffix
    new\_name = old\_name[:index] + '[backups]' + postfix

    # Create and open a new file
    with open(new\_name, 'wb') as new\_obj:
        # Defines the size of each read
        chunk = 1024 * 100

        while True:
            # Read data from existing objects
            content = file\_obj.read(chunk)

            # After reading the content, terminate the cycle
            if not content:
                break

            # Write the read data to the new object
            new\_obj.write(content)

The functions of the two methods are the same.

4. Another little exercise

Requirement: binary file reading (the implementation method is the same as above)

python

# Read mode
# Tread text file (default)
# b read binary files

file\_name = "hello.txt"

with open(file\_name , 'rb') as file\_obj:
    # When reading a text file, size is in characters
    # When reading binary files, size is in bytes
    # print(file\_obj.read(100))

    # Write out the read content
    # Define a new file
    new\_name = 'aa.txt'

    with open(new\_name , 'wb') as new\_obj:

        # Defines the size of each read
        chunk = 1024 * 100

        while True :
            # Read data from existing objects
            content = file\_obj.read(chunk)

            # After reading the content, terminate the cycle
            if not content :
                break

            # Write the read data to the new object
            new\_obj.write(content)

Note: plain text files can also be read using binary methods.

  • About bloggers: comments and private messages will be replied at the first time. perhaps Direct private letter I.
  • Copyright notice: all articles on this blog are in English unless otherwise stated BY-NC-SA License agreement. Reprint please indicate the source!
  • Support bloggers: if you think the article is helpful to you, you can click * * [recommend] (javascript:void(0) in the lower right corner of the article) 😉]** once.

Topics: Python Back-end computer