程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

I learned the basics of Python at station B. learning 13: file operation (Continued)

編輯:Python

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 )


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved