python file operations and modules

catalogue

File operation

File backup

File location

Module import

os module fabrication

File operation

General steps of file operation:

Open file, read / write file, save file  , Close file

The open function is used to open a file. Generally, our default code is gbk. The best habit is that we open another file and assign it an encoding type.

Write file

fobj=open('./Test.txt','w',encoding='utf-8') #The front is the path, and the back is the opening mode w, write only
#Start read / write operation
fobj.write('On the vast sea')
fobj.write('The strong wind swirled the dark clouds')
fobj.close() #Close the file before writing to it
Write data in binary form (wb)
fobj=open('Test_1.txt','wb')#wb is written in binary
fobj.write('Between the dark clouds and the sea'.encode('utf-8'))
fobj.close()

Add (a)

fobj=open('Test.txt','a')#a is appended, and ab is not overwritten. It is appended in binary mode
fobj.write('On the vast sea')
fobj.write('The strong wind swirled the dark clouds')
fobj.write('Between the dark clouds and the sea\n')
fobj.write('Petrels are like black lightning\n')
fobj.close()

Read data

f=open('Test.txt','r')
print(f.read()) #read reads all the data
print(f.read(10)) #The number of characters read is 10
print(f.read())#After reading 10 bytes above, follow the following reading
print(f.readline())#Read a line
print(f.readlines())#Read all rows and return a list
f.close()

Read data in binary form (wb)

f=open('Test.txt','rb')
data=f.read()
print(data)
print(data.decode('gbk')) #decode
f.close()

with is a context management object

Its advantage is that it can automatically release open associated objects

with open('Test.txt','a') as f:
    #print(f.read())
    f.write('I think so python Very easy to learn\n')

Summary:

Several operation modes of file reading and writing read R + Rb +

R + read only, suitable for ordinary scenes

rb rb + applies to files such as files, pictures, videos and audio

write w w+ wb+ wb a ab w.

wb+ w + creates files every time

When reading and writing binary, we should pay attention to coding. By default, the file we write is gbk

a ab a + append (at the end of the file pointer) on the basis of the original file, and a new file will not be created every time

File backup  

The script is used to complete the automatic backup. The user is required to enter the file name to complete the automatic backup

#Backup of files
def copyfile():
    #Accepts the file name entered by the user
    old_file=input('Please enter a file name to back up:')
    file_list=old_file.split('.') #Separate file names and suffixes
    #Construct a new file name. Add the suffix of the backup
    new_file=file_list[0]+'_backups.'+file_list[1]
    old_f=open(old_file,'r') #Open the file that needs to be backed up
    new_f=open(new_file,'w') #Open a new file in write mode. If the file does not exist, create it
    content=old_f.read() #Read out the contents of the file
    new_f.write(content) #Write content to backup file
    old_f.close()
    new_f.close()
    pass

copyfile()

The above code can be optimized

def copyBigfile():
    #Accepts the file name entered by the user
    old_file=input('Please enter a file name to back up:')
    file_list=old_file.split('.') #Separate file names and suffixes
    #Construct a new file name. Add the suffix of the backup
    new_file=file_list[0]+'_backups.'+file_list[1]
    try:
        #Monitor logic to process
        with open(old_file,'r') as old_f,open(new_file,'w') as new_f:
            while True:
                content=old_f.read(1024) #1024 characters at a time
                new_f.write(content)
                if len(content)<1024:
                    break
    except Exception as msg:
        print(msg)

    pass

copyBigfile()

File location

File positioning refers to the position read by the current file pointer and the cursor position. In the process of reading and writing files, if you want to know the current location, you can use tell() to get it.

with open('Test.txt','r') as f:
    print(f.read(3))
    print(f.tell()) #6
    print(f.read(2))
    print(f.tell()) #10
    pass

If you read Chinese, a word is equivalent to two bytes

The truncate function can intercept the source file

fobjB=open('Test.txt','r')
print(fobjB.read())
fobjB.close()
print('Intercepted data........')

fobjA=open('Test.txt','r+')
fobjA.truncate(15) #Keep the first 15 characters
print(fobjA.read())
fobjA.close()

If you need to navigate to another location to operate in the process of operating the file, use seek(). seek(offset, from) has two parameters, offset, offset unit byte, negative number is back offset, positive number is forward offset, from position: 0 indicates the beginning of the file, 1 indicates the current position, and 2 indicates the end of the file.

with open('Test_backups.txt','rb') as f:
    f.seek(4,0) #The cursor starts from the position of 0 and moves 4 characters like the front [right]
    data=f.read(2)
    print(data.decode('gbk'))
    f.seek(-2,1) #It is equivalent to setting the cursor to the position of 0
    print(f.read(4).decode('gbk'))
    f.seek(-6,2) #2 indicates that the cursor moves back 6 characters at the end
    print(f.read(4).decode('gbk'))
    pass

1 for the above case, the file is opened in the mode of 'r'. In the text file, the binary option is not used to open the file. Only the relative position is allowed to be calculated from the beginning of the file. If it is calculated from the end of the file or the current calculation, an exception will be thrown.

Module import

There are two methods for module import:

1.import xxx

The following three steps will occur when import ing a module for the first time

1. Open the module file

2. Execute the file corresponding to the module and throw all the names generated during execution into the module namespace  

3. In the program, there will be a module name pointing to the module namespace.

2.from...import

  from...import the first import takes place in three steps

1. Create a module space based on the module

  2. Execute the file corresponding to the module and throw all the names generated during execution into the module namespace

  3. Take a name in the namespace of the current executable file. Changing the name directly points to a name in the module, which means that it can be used directly without adding any prefix

  Advantages: no prefix, the code is more concise

Disadvantages: it is easy to conflict with the name in the namespace in the current execution file

Similarities between the two methods:

1. The file corresponding to the module will be executed, and the module namespace will be generated

2. When calling functions, both need to go to the definition to find the scope relationship

difference:

import needs to be prefixed. from...import does not need to be prefixed

from time import * # import all

Import import method

import time
print(time.ctime()) #Calling functions in modules

from...import import method

from time import ctime,time #Partial import
print(ctime()) #Direct use

os module fabrication  

The os module operates on files. We explain the usage of some functions in the os module in the form of code.

os.rename('Test.txt','Test_rename.txt') #File rename
os.remove('Files to delete.py') #Delete file
os.mkdir('TestCJ')#To create a folder, only one level directory can be created
os.rmdir('TestCJ') #To delete a folder, you can only delete an empty directory
os.makedirs('d:/python/sub') #Create multi-level file directory

#If you want to delete a non empty directory, call the shutil module
shutil.rmtree('d:/python/sub') #Non empty delete

#Get current directory
print(os.getcwd())
#Splicing of paths
print(os.path) #Path of os module
print(os.path.join(os.getcwd(),'venv'))

There are two ways to get a list of directories in python

Method 1:

listRs=os.listdir('G:/') #Method 1
for dirname in listRs:
    print(dirname)
    pass

Method 2: scanner and with are used together. In this way, the context manager will automatically release resources after the iterator traversal is completed

with os.scandir('G:/') as entries:
    for entry in entries:
        print(entry.name)
        pass
    pass

Print files in directory

basePath='g:/'
for entry in os.listdir(basePath):
    # if os.path.isfile(os.path.join(basePath,entry)): #Determine whether it is a file
    #     print(entry)
    if os.path.isdir(os.path.join(basePath,entry)): #Determine whether it is a directory
        print(entry)

Here are some simple additions:

1. The role of the all variable if it exists in a file__ all__ Variable, which means that the elements of this variable will be imported when imported from XXX * and will not affect import xxx all

2.if __name__=='__main__' This code is to ensure that the code below if will not be executed when called elsewhere.

Tags: Python

Posted on Sun, 19 Sep 2021 04:24:06 -0400 by ktsirig