Last one : I am here b Station learning python Basic learning 12 : File operations
One 、 File backup
1、 step :
Receive the file name entered by the user -> Plan the backup file name -> Backup file write data
2、 Code implementation :
#1 Receive the target file name entered by the user
old_name = input(' Please enter the file name to be backed up :')
#2 Plan the backup file name
index = old_name.rfind('.') # Extract the subscript of the suffix point of the file
if index > 0:
postfix = old_name[index:] # Only valid files are backed up
new_name = old_name[:index] + '[ Backup ]' + postfix # Organize new file names
#3 Backup file write data
old_f = open(old_name,'rb')
new_f = open(new_name,'wb') # Open the source file and backup file
# Write source file data to backup file
while True:
con = old_f.read(1024)
if len(con) == 0:
break
new_f.write(con)
# Close file
old_f.close()
new_f.close()
Two 、 File operations
stay python The operation of files and folders in the os Module related functions
1、rename() rename
example :os.rename(‘1.text’,‘10.text’)
Will file 1.text Rename it to 10.text
2、remove() Delete file
example :os.remove(‘1.text’)
Delete 1.text file ( There is no mistake in the times )
3、 ... and 、 Folder operation
Same demand os modular
1、mkdir() Create folder
example :os.mkdir(‘aa’)
Create folder aa( The times have been wrong )
2、rmdir() Delete folder
example :os.rmdir(‘aa’)
Delete folder aa
3、getcwd() Return the directory path where the current folder is located
example :print(os.getcwd())
Print the current file path
4、chdir() Change directory path
example :os.chdir(‘aa’)
Change current path to folder aa Next
5、listdir() Returns all files in a folder in the form of a list
example :print(os.listdir(‘aa’))
take aa All files in the folder , Return... As a list
6、1、rename() rename
example :os.rename(‘aa’,‘bb’)
Put the folder aa Rename it to bb
Four 、 Simple application cases
Case study : Batch modify file name , You can add and delete specified strings
import os
# Construct conditional data
flag = 1
# Find all the files
file_list = os.listdir()
# Construction name
for i in file_list:
if flag == 1:
new_name = 'python-' + i
elif flag == 2:
num = len('python-')
new_name = i[num:]
# rename
os.rename(i,new_name)
(flag=1, Perform prefix adding operation ,flag=2 Delete . Delete the runtime if any .idea The folder will report an error , You need to delete it before you can run )