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

Fundamentals of python (5)

編輯:Python

List of articles

  • Document processing
    • application
    • Basic operation
      • open
      • Writing method of file object
    • File backup
    • File and folder operations
  • exception handling
  • Project practice

Document processing

application

(1) file :
(2) File operations : open 、 close 、 read 、 Write 、 Copy
(3) Contents of file operation : Read the content 、 Write ⼊ Content 、 Backup content
All in all , The role of file manipulation : Put some inside Rong ( data ) Store it , The next time the program executes Use it directly , There is no need to make a new one .

Basic operation

Open file ——> Read, write, etc ——> Close file

open

open ⼀ An existing ⽂ Pieces of , Or create ⼀ A new ⽂ Pieces of .

open(name,mode)
name: Refers to the string of the open target file name ( It can contain the specific path where the file is located )
mode: Set the mode of accessing files ( Access pattern ): read-only write in Additional

r+: An error is reported when there is no such document ; File pointer at the beginning , Can read and take out data
w+: There is no such document , The file will be created ; File pointer at the beginning , It will cover the original content
a+: If there is no file, create a new file , File pointer at the end , Unable to read data ( There is no data after the file pointer )

# Create a file object 
f=open('test.txt','w')

The default access mode is r, It can be omitted

Writing method of file object

Write : object .write(" Content ”)

f=open('text.txt','w')
f.write("hello")
f.close()
# w and a Pattern : If ⽂ If the piece does not exist, the ⽂ Pieces of ; If ⽂ Pieces exist ,w The mode is cleared before writing ⼊,a Append directly to the end of the mode .r Pattern : If ⽂ If the file does not exist, an error is reported .

read :

 File object .read(num)
#num To express from ⽂ Of the data read in the file ⻓ degree ( Unit is byte ), If there is no transmission ⼊num, Then it means reading ⽂ All the data in the piece .
# If there is a line break in the file content ( The bottom is \n), It can lead to read The number of written parameters read does not match the parameters seen 
File object .readlines()
#readlines May, in accordance with the ⾏ Of ⽅ Put the whole ⽂ The contents of the document go into ⾏⼀ Secondary read , And back to ⼀ A list , Each of them ⼀⾏ The data is ⼀ Elements .
f = open('test.txt')
content = f.readlines()
# ['hello world\n', 'abcdefg\n', 'aaa\n', 'bbb\n', 'ccc']
print(content)
# close ⽂ Pieces of 
f.close()
readline(): Read one line at a time
f = open('test.txt')
content = f.readline()
print(f' The first ⼀⾏:{
content}')
content = f.readline()
print(f' The first ⼆⾏:{
content}')
# close ⽂ Pieces of 
f.close()
seek(): Used to move the file pointer
File object .seek( Offset , The starting position )
#0:⽂ The beginning of the piece 1: The current position 2:⽂ End of piece 
seek(0,0) seek(0)
# Put the file pointer at the beginning without offset 

close :

⽂ Objects .close()

File backup

⽤ Households lose ⼊ At present ⽬ record Next arbitrarily ⽂ Piece name , The program completes the ⽂ Piece Backup function ( Backup ⽂ The name of the piece is xx[ Backup ] suffix , for example :test[ Backup ].txt).

1. receive ⽤ Households lose ⼊ Of ⽂ Piece name
2. Planning backups ⽂ Piece name
3. Backup ⽂ Piece writing ⼊ data

#1. Accept user input target file name 
old_name=input(" Please enter the file name you want to back up ")
#2. Plan the backup file name 
#2.1 First extract the subscript of the suffix 
index=old_name.rfind(".")
if index>0:
postfix = old_name[index:]
#2.2 File name of the organization backup xx[ Backup ] suffix ( section )
new_name = old_name[:index] +'[ Backup ]'+postfix
#3. Backup file write data 
#3.1: Open source ⽂ Copy and backup ⽂ Pieces of 
#3.2: Will source ⽂ Piece data write ⼊ Backup ⽂ Pieces of ( Uncertain file size , Loop in )
#3.3: close ⽂ Pieces of 
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()

File and folder operations

(1) Import os modular

import os

(2) Use os Module related functions

os. Function name ()
rename( Destination folder , New file name )# File rename 
remove( Destination filename )# Delete file 
mkdir( File name )# Create folder 
rmdir( Folder name )# Delete folder 
getcwd():# Get the default path where the current file is located 
chdir( Catalog )# Change the default directory 
# stay aa Create in folder bb
os.chdir('aa')
os.mkdir('bb')
listdir( Catalog )# Get directory list 
# Get all the files in a folder , Return an object 

exception handling

When detected ⼀ When you make a mistake , Interpreter on ⽆ The law goes on ⾏ 了 , back ⽽ There is ⼀ Some wrong tips , That's what's called " abnormal ".

try:
The code that could have an error
except:
If there is an exception to the execution of the code
try:
f=open("text.txt",'r')
except:
f=open("text.txt",'w')

Catch the specified exception :
1. If you try to hold ⾏ The exception type of the code is different from the exception type to be caught ⼀ Cause , be ⽆ Can't catch exception .
2.⼀ like try Next ⽅ Only put ⼀⾏ Try to hold ⾏ Code for .

Catch all exceptions :

In exception else: Code to execute when there is no exception
In exception finally: Code to be executed whether or not an exception occurs

# Custom exception : If the password length is less than three digits, an error will be reported 
class Short(Exception):
def _init_(self,length,min_len):
self.length=length
self.min_len=min_len
def _str_(self):
return f' The length you entered is {
self.length}, No less than {
self.min_len} Characters
def main():
try:
con = input(' Please lose ⼊ password :')
if len(con) < 3:
raise ShortInputError(len(con), 3)
except Exception as result:
print(result)
else:
print(' The password has been entered ⼊ complete ')

Project practice

demand : Batch modify file name , You can add a specified string , It can also delete the specified string

step :1. Sets the identity of the string to be added or deleted
2. Get specified ⽬ All recorded ⽂ Pieces of
3. The original ⽂ Add piece name / Delete the specified string , Construct a new name
4.os.rename() rename

import os
# Set rename ID : If 1 The specified character is added ,flag The value is 2 The specified character is deleted flag = 1
# Get specified ⽬ record 
dir_name = './'
# Get specified ⽬ Recorded ⽂ Piece list 
file_list = os.listdir(dir_name)
# Traverse ⽂ Items in the list ⽂ Pieces of 
for name in file_list:
# Add specified character 
if flag == 1:
new_name = 'Python-'+name
# Delete specified characters 
elif flag == 2:
num = len('Python-')
new_name = name[num:]
# Print new ⽂ Piece name , Test program correctness 
print(new_name)
# rename 
os.rename(dir_name+name, dir_name+new_name)

The transmission of exceptions :
1. Try read-only ⽅ Open type test.txt⽂ Pieces of , If ⽂ If the file exists, read ⽂ It's about ,⽂ If the file does not exist, it will prompt ⽤ You can .
2. Reading content requires : Try looping through the content , If... Is detected during reading ⽤ The accident ended ⽌ Program , be except Catch exceptions and prompt ⽤ Household .


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