Python file manipulation and management guide: opening, reading, writing, and managing files

File

Use Python programs to add, delete, modify and check various files in the computer

I/O(Input / Output)

Steps to operate files:

  1. open a file
  2. Perform various operations (read, write) on the file and then save it
  3. close file

open a file

file_name = 'demo.txt'
file_obj = open(file_name)
print(file_obj)

Tip: The information output here is the file object information.

Use the with ... as statement to open the file

file_name = 'hello'

try:
    with open(file_name) as file_obj :
        print(file_obj.read())
except FileNotFoundError:
    print(f'{
      
      file_name} 文件不存在~~')

Tip: The with … as statement can automatically close the file at the end of the code block.

Read file contents

file_name = 'demo2.txt'

try:
    with open(file_name, encoding='utf-8') as file_obj:
        content = file_obj.read()
        print(content)
except FileNotFoundError:
    print(f'{
      
      file_name} 这个文件不存在!')

# 或者逐行读取文件内容

file_name = 'demo.txt'

try:
    with open(file_name, encoding='utf-8') as file_obj:
        for line in file_obj:
            print(line)
except FileNotFoundError:
    print(f'{
      
      file_name} 这个文件不存在!')

How to read large files

file_name = 'demo.txt'

try:
    with open(file_name, encoding='utf-8') as file_obj:
        file_content = ''
        chunk = 100
        while True:
            content = file_obj.read(chunk)
            if not content:
                break
            file_content += content

except FileNotFoundError:
    print(f'{
      
      file_name} 这个文件不存在!')

print(file_content)

Tip: For larger files, use a loop to read the content to avoid memory leaks caused by reading the entire content at once.

Read line by line and read all lines

import pprint
import os

file_name = 'demo.txt'

with open(file_name, encoding='utf-8') as file_obj:
    for line in file_obj:
        print(line)

Or use readline()the and readlines()methods:

with open(file_name, encoding='utf-8') as file_obj:
    print(file_obj.readline(), end='')
    print(file_obj.readline())
    print(file_obj.readline())

# 或者

with open(file_name, encoding='utf-8') as file_obj:
    r = file_obj.readlines()
    pprint.pprint(r[0])
    pprint.pprint(r[1])
    pprint.pprint(r[2])

Write file operation

First we need to use open()the function to open a file and operate it, and then use write()the method to write content to the file.

file_name = 'demo5.txt'
with open(file_name , 'x' , encoding='utf-8') as file_obj:
    file_obj.write('aaa\n')
    file_obj.write('bbb\n')
    file_obj.write('ccc\n')
    r = file_obj.write(str(123)+'123123\n')
    r = file_obj.write('今天天气真不错')
    print(r)

File location

seek()

seek()The function is used to modify the file reading position and requires two parameters:

  • location to switch to
  • How to calculate this position

This function has three ways to calculate position:

  • 0 Calculate from scratch, default value
  • 1 Calculated from current position
  • 2 Count from the last position
with open('demo2.txt','rt' , encoding='utf-8') as file_obj:
    file_obj.seek(9)
    print(file_obj.read())
    print('当前读取到了 -->',file_obj.tell())

tell()

Use tell()the function to view the current read position.

with open('demo2.txt','rt' , encoding='utf-8') as file_obj:
    file_obj.seek(9)
    print(file_obj.read())
    print('当前读取到了 -->',file_obj.tell())

close file

Closing a file is a very important operation, it frees up operating system resources and ensures that the file is closed properly after use.

There are several ways to close files in Python:

  1. Using close()method: You can directly call close()the method of the file object to close the file.
f = open('filename.txt')
# 使用文件对象进行读写操作
f.close()  # 关闭文件
  1. Use withstatement: withThe statement will automatically close the file after the code block is executed, and the file will be closed normally even if an exception occurs.
with open('filename.txt') as f:
    # 使用文件对象进行读写操作
    # 不需要手动调用 close() 方法来关闭文件

Regardless of the method used, closing files is a good programming practice. This avoids file handle leaks and resource waste.

In addition, there are some things to note:

  • When using withthe statement, there is no need to manually call close()the method to close the file.
  • When using close()the method to close a file, be sure to close the file after the file operation is completed to avoid errors caused by closing the file during the file operation.
  • A file may not be closed if an exception occurs during a file operation and the file is not properly handled or closed. Therefore, withthis situation is better handled using the statement.
  • For performance reasons, the Python interpreter may delay closing files in some cases. However, in order to maintain good programming habits, we should always actively close files after using them.

In short, closing files is a good programming practice to ensure the correct release of files and system resources. It is recommended to always develop the habit of closing files in your code, especially when the file operation is complex or the file needs to be opened for a long time.

File management

Use osthe module to manage files and directories.

Get directory structure

Use os.listdir()the function to get the directory structure under the specified directory.

import os

r = os.listdir()
print(r)

Get current directory

Use os.getcwd()the function to get the current directory.

import os

r = os.getcwd()
print(r)

Switch current directory

Use os.chdir()the function to switch the current directory, which is equivalent to cdthe command.

import os

os.chdir('c:/')
r = os.getcwd()
print(r)

Create a directory

Use os.mkdir()the function to create a new directory under the specified path.

import os

os.mkdir("aaa")

delete directory

Use os.rmdir()the function to delete empty directories under the specified path.

import os

os.rmdir('abc')

Delete Files

Use os.remove()the function to delete files under the specified path.

os.remove('aa.txt')

Rename file

Use os.rename()the function to rename or move files under a specified path.

os.rename('aa.txt','bb.txt')
os.rename('bb.txt','c:/users/lilichao/desktop/bb.txt')

Summarize

This article introduces the operation and management of files in Python. First, we learned how to open files, including using open()functions and with ... asstatements to open files, and it is a good programming practice to properly close files after the operation is complete. We then discussed how to read the contents of a file, including reading the entire file and reading the file line by line. For large files, we introduce a way to read the file block by block to avoid memory issues. Next, we learned how to perform file write operations, including writing new files and appending content to existing files. We also looked at two important methods of file positioning: seek()and tell(), which can be used to control and obtain the current location of a file. In terms of file management, we learned how to get the directory structure, get the current directory, switch the current directory, create a directory, delete a directory, and delete and rename files. The knowledge of these file operations and management is very important for daily file processing tasks and is also an essential skill for programmers.

By studying this article, readers can master the basic skills of file operation and management, be able to read and write files safely, and perform simple file and directory management operations. This will help with day-to-day file processing needs and improve code readability and maintainability. At the same time, understanding the basic principles of file operation and management can lay a solid foundation for further learning more advanced file operation and management techniques. Let’s become more proficient at handling files in Python programming!

This article ends here, thank you for watching!


Recommended Python boutique columns

Basic knowledge of python (0 basic introduction)

[Python basic knowledge] 0.print() function
[python basic knowledge] 1. Data types, data applications, data conversion
[python basic knowledge] 2. if conditional judgment and condition nesting
[python basic knowledge] 3.input() Functions
[Basic knowledge of python] 4. Lists and dictionaries
[Basic knowledge of python] 5. For loops and while loops
[Basic knowledge of python] 6. Boolean values ​​and four types of statements (break, continue, pass, else)
[Basic knowledge of python] 7. Practical operation - Use Python to implement the "Word PK" game (1)
[Python basic knowledge] 7. Practical operation - Use Python to implement the "Word PK" game (2)
[Python basic knowledge] 8. Programming thinking: how to Solving problems - Thinking Chapter
[Basic Knowledge of python] 9. Definition and calling of functions
[Basic Knowledge of Python] 10. Writing programs with functions - Practical Chapter
[Basic Knowledge of Python] 10. Using Python to implement the rock-paper-scissors game - Function Practice Operation Chapter
[Python Basics] 11. How to debug - Common error reasons and troubleshooting ideas - Thinking Chapter
[Python Basics] 12. Classes and Objects (1)
[Python Basics] 12. Classes and Objects (2)
[Python Basics] Knowledge] 13. Classes and objects (3)
[Basic knowledge of python] 13. Classes and objects (4)
[Basic knowledge of python] 14. Building a library management system (practical operation of classes and objects)
[Basic knowledge of python] 15. Coding basic knowledge
[Basic knowledge of python] 16. Fundamentals of file reading and writing and operations
[Basic knowledge of python] 16. Python implementation of "Ancient poem dictation questions" (File reading, writing and coding - practical operation)
[Basic knowledge of python] 17. The concept of modules and How to introduce
[python basics] 18. Practical operation - using python to automatically send mass emails
[python basics] 19. Product thinking and the use of flow charts - thinking
[python basics] 20. python implementation of "what to eat for lunch" ( Product Thinking - Practical Operation)
[Basic knowledge of python] 21. The correct way to open efficiently and lazily - Graduation
[python file processing] Reading, processing and writing of CSV files
[python file processing] Excel automatic processing (using openpyxl)
[python file processing]-excel format processing


python crawler knowledge

[python crawler] 1. Basic knowledge of crawlers
[python crawler] 2. Basic knowledge of web pages
[python crawler] 3. First experience with crawlers (BeautifulSoup analysis)
[python crawler] 4. Practical crawler operation (dish crawling)
[python crawler] 5 .Practical crawler operation (crawling lyrics)
[python crawler] 6. Practical crawler operation (requesting data with parameters)
[python crawler] 7. Where is the crawled data stored?
[python crawler] 8. Review the past and learn the new
[python crawler] 9. Log in with cookies (cookies)
[python crawler] 10. Command the browser to work automatically (selenium)
[python crawler] 11. Let the crawler report to you on time
[python crawler] 12. Build your crawler army
[python crawler] 13. What to eat without getting fat (crawler practical exercise)
[python crawler] 14. Scrapy framework explanation
[python crawler] 15. Scrapy framework practice (popular job crawling Take)
[python crawler] 16. Summary and review of crawler knowledge points

Guess you like

Origin blog.csdn.net/qq_41308872/article/details/132858231