file backup operation

# 1.txt,1.py 1.mp3  1.avi
# Allow the user to enter any file -- backup
# Open the source file, open the backup file -- read the source file, and write the backup file -- close both files
import them

# get all files in this path
file_list = os.listdir('./')
print(file_list)
file_name = input('Please enter the name of the file to be backed up:')
if file_name in file_list:
    # sound.mp3 == sound_backup.mp3 -- add backup to the name before the dot -- finx('aa')
    # str1 = 'sound.mp3'  -- aa.bb.mp3
    # print(str1.find('.'))  rfind('.')
    # str2 = 'sound.aa.mp3'  # str2[:8] + back_up  +  str2[8:]
    # print(str2.rfind('.'))
    index = file_name.rfind('.')
    # print(index)
    # spell a new name
    new_name = file_name[:index] + "_backup" + file_name[index:]
    # print(new_name)
    # open a file
    src_f = open(file_name, 'rb') # audio file, so open in binary mode
    new_f = open(new_name, 'ab')
    # Read data from the source file, write data to the new file
    # src_f.read() -- read is to read all at once, if the file is too large, there will be problems, loop read loop write
    # When there is no data, the read and write will not be performed in a loop -- the data length is 0 len() == 0
    while True:
        # Find a variable to save the data read each time
        data = src_f.read(1024 * 1024)
        print(data)
        if len(data) == 0:
            break
        new_f.write(data)

    # Close two files -- first close the backup and then close the source file
    new_f.close()
    src_f.close()
else:
    print('The file does not exist')

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325855995&siteId=291194637