Python notes 15 - file operations

Python notes

File operation

I Role of file operation

Function: store some contents (data) so that the next execution of the program can be used directly without remaking.

II Basic operation of files

1. Document operation steps

  1. Open file
  2. Read and write operations
  3. Close file

Note: it can refer to opening and closing files without any reading and writing operations.

1.1. open

In python, you can use the open() function to open an existing file or create a new file.
Syntax:

open(name,mode)

Name: the string of the name of the target file to be opened (which can contain the specific path where the file is located).
Mode: set the mode of opening files (access mode): read-only, write, append, etc.

  • Open file mode
    |Mode description|
    |:----😐:-----|
    |r| open the file as read-only. The pointer to the file is placed at the beginning of the file. This is the default mode|
    |rb| open the file in binary format for read-only. The file pointer is placed at the beginning of the file. This is the default mode|
    |r + | open a file for reading and writing. The file pointer is placed at the beginning of the file|
    |rb + | open the file in binary format for reading and writing. The file pointer is placed at the beginning of the file|
    |w| open file is only used for writing. If the file exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, a new file is automatically created|
    |wb| open the file in binary format for writing only. If the file exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, a new file is automatically created|
    |w + | open a file for reading and writing. If the file exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, a new file is automatically created|
    |wb + | open the file in binary format for reading and writing. If the file exists, open the file and edit it from the beginning, that is, the original content will be deleted. If the file does not exist, a new file is automatically created|
    |A | open a file for appending. If the file already exists, the file pointer is placed at the end of the file. That is, when adding new content, the new content will be added after the existing content. If the file does not exist, a new file is automatically created|
    |ab| open the file in binary format for appending. If the file already exists, the file pointer is placed at the end of the file. That is, when adding new content, the new content will be added after the existing content. If the file does not exist, a new file is automatically created|
    |A + | open a file for reading and writing. If the file already exists, the file pointer is placed at the end of the file. When the file is opened, it will be in append mode. If the file does not exist, a new file will be automatically created|
    |ab + | open the file in binary format for appending. If the file already exists, the file pointer is placed at the end of the file. If the file does not exist, a new file is automatically created for reading and writing|

  • Examples

f1=open('test.txt','w') # f1 is the file object of the open function

1.2. File object method

  • write

    • grammar
    File object.write('content')
    
    • Examples
    f1=open('test1.txt','w')
    
    f1.write('Hello World!')
    
    f1.close()
    
  • read

    • read()
    File object.read(num)
    

    Note: num indicates the length of data to be read from the file (in bytes). If num is not passed in, all data of the file will be read.

    • readlines()
      readlines can read the contents of the whole file at one time in the form of lines, and return a list, in which the data of each line is an element.
    f1=open('test2.txt')
    
    content=f1.readlines()
    
    print(content)
    
    f1.close
    
    • readline()
      readline() reads one line at a time.
    f1=open('test2.txt')
    
    content=f1.readline()
    
    print(f'First line:{content}')
    
    content=f1.readline()
    
    print(f'Second line:{content}')
    
    f1.close
    
    • seek()
      Function: used to move the file pointer.
      Syntax:
    File object.seek(Offset,Starting position)
    

    Starting position:
    0: beginning of file
    1: Current location
    2: End of file

1.3. close

File object.close()

III File backup

old_name=input('Please enter the file name to back up:')
# Extract the position subscript of the suffix point of the file
index=old_name.rfind('.')
# Determine whether it is a valid file name
if index>0:
	postfix=old_name[index:]
# New file name
new_name=old_name[:index]+'[backups]'+postfix
# Open file
old_f=open(old_name,'rb')
new_f=open(new_name,'wb')
# write in
while True:
	con=old_f.read(1024)
	if len(con)==0:
		break
	new_f.write(con)
# Close file
old_f.close()
new_f.close()

IV Operation of files and folders

os module must be imported

import os

1. Rename the file

os.rename(Destination file name,New file name)

2. Delete file

os.remove(Destination file name)

3. Create a folder

os.mkdir(Folder name)

4. Delete folder

os.rmdir(Folder name)

5. Get the current directory

os.getcwd(Folder name)

6. Change the default directory

os.chdir(Folder name)

7. Get directory list

os.listdir(catalogue)

15
Levi_5

Keywords: Python Pycharm

Added by Janus13 on Tue, 22 Feb 2022 02:08:09 +0200