Objective:
- Concept of documentation
- Basic file operations
- Common operations on files/folders
- How text files are encoded
1. The concept of documentation
1.1 Concept and role of documentation
A computer file, which is a piece of data stored on some kind of long-term storage device
Long-term storage devices include: hard drives, USB drives, removable drives, CD-ROMs ----
The role of documentation:
Store data for a long time and use it when needed
1.2 How documents are stored
- In computers, files are saved on disk as binary
Text and binary files
- text file
- It can be viewed with text editing software
- It's still essentially binary.
- Example: Python source file
- binary file
- Saved content is not intended to be read directly, but is provided for use by other software
- For example: image files, audio files, video files, etc.
- Binary files cannot be viewed directly with a text editor
2. Basic operation of documents
2.1 Sets of manipulated documents
In computers, the routine to manipulate files is very fixed and consists of three steps:
- Open file
- Read and write files
- Read: reads the contents of the file into memory
- Write: Write the contents of memory to a file
- Close file
2.2 Functions/methods to manipulate files
- 1 function and 3 methods to remember to manipulate files in Python
serial number | Functions/Methods | clarification |
---|---|---|
1 | open | Open the file and return the file operation object |
2 | read | Reads the contents of a file into memory |
3 | write | Write the specified content to a file |
4 | close | Close file |
- The open() function opens the file and returns the file object.
- The read/write/close methods all need to be called from a file object.
2.3 read method - reading a file
- The first argument to the open function is the name of the file to be opened (file names are case sensitive)
- If the file exists, return the file operation object
- If the file does not exist, an exception is thrown
- The read method reads and returns the entire contents of a file at once.
- The close method closes the file.
- If you forget to close a file, it can cause a drain on system resources and can affect subsequent access to the file
- Note: After the method executes, it moves the file pointer to the end of the file
- Tip:
- In development, it is common to write open and close code first, and target file read/write operations in the middle!
# Get the file operation object (file) file = open("") #Read text = () print(text) # Close the file () ''' Running Result I am Chinese Oh nidie Chinese '''
- File Pointer File Pointer
- File pointer Marks the location from which to start reading.
- When opening a file for the first time, the file pointer will usually point to the beginning of the file
- When the read method is executed, the file pointer moves to the end of the read content
- By default it moves to the end of the file
- Think: If you execute the read method once and read everything, can you call the read method again and still get the contents?
- Answer: No. After the first read, the file pointer moves to the end of the file, and another call will not read any content.
File Pointer Demo
# Get the file operation object (file) file = open("") #Read text = () # View the length of the read file (14) print(len(text)) # Output the read file print(text) print("*"*30) #Re-read the file text = () print(text) # Empty print(len(text)) # (0) # Close the file () """ Run the results: 14 I am Chinese oh nidie Chinese ****************************** 0 """
2.4 Ways to open a file
- The open function opens in read-only mode by default and returns the file object
The syntax is as follows:
f = open( " filename " , " access method " )
Tip: Frequent movement of the pointer will affect the efficiency of reading and writing files, and more often than not, the development of read-only, write-only way to manipulate files.
2.5 Reading file contents by line
- The read method by default reads the entire contents of the file into memory at once.
- If the file is too large, it can be a serious memory hog
readline method:
- Can read one line at a time
- method executes, it moves the pointer to the next line, ready to read again the
The correct posture for reading large files:
# Open the file file = open("") while True: #Read a line text = () # Determine if content is read if text == "": # or if not text. print(type(text)) #<class 'str'> break # Every time you read to the end there's a \n print(text,end="") """ Run the results: python1 one python2 two python3 three python4 four <class 'str'> """
2.6 File Read and Write Case - Copying Files
Objective: To implement the file copying process in code
Small file replication
Open an existing file, read the full contents, and write to another file
# Copying small files mode 1 file_read = open("","r") file_write = open("","w") text_1 = file_read.read() text_2 = file_write.write(text_1) file_write.close() file_read.close() # Copy small files way 2 recommended (with keyword, will automatically free up space in file object) test = None with open("","r") as file: test = () with open("","w") as file: (test)
Large File Replication
Open an existing file, read the contents line by line, and write them sequentially to another file.
# Large file duplication file_read = open("Five Stroke Roots","rb") file_write = open("Five Stroke Roots","wb") while True: text = file_read.readline() In #python, all conversions are True except '', "", 0, (), [], {}, and None, which are False. That is, strings are always converted to True if they are not empty. if not text: break file_write.write(text) file_read.close() file_write.close()
2.7 Functions in file reading and writing
file reading- Python 3.10.1 Documentation
3. Common management operations for files/directories
- In Terminal/File Browsing, you can perform regular file/directory management operations, such as
Create, rename, delete, change roadkill, view catalog contents ........
- In Python, if you want to do this programmatically, you need to import the os module
File Operations:
Catalog Operations:
Tip: File or directory operations are supportedrelative path
cap (a poem)Definitely Lugin.
4. How text files are encoded
pass
# -*- coding: utf8 -*-
# -*- coding: utf-8 -*-
# -*- coding: gbk -*-
5. Expansion: eval function
The eval function is very powerful - it evaluates a string as if it were a valid expression and returns the result.
# -*- coding: gbk -*- #Basic math calculations print(eval("1+1")) #String repetition print(eval("'*'*30")) # Convert strings into lists print(type(eval("[1,2,3,4,5]"))) # Convert strings into tuples print(type(eval("(1,2,3,4,5)"))) # Convert strings into dictionaries print(type(eval("{'name':'Apple','age':18}")))
Case - Calculator
input_str = input("Enter the math problem.") print(eval(input_str)) ''' Run: Enter the arithmetic problem 1+1 2 '''
Note: Never use eval to directly convert the result of input during development.
The above mentioned is a small introduction to Python file manipulation, I hope to help you. Here also very much thank you for the support of my website!