[100 days proficient in python] Day19: Python file and directory operations_basic file operations

Table of contents

Column guide 

1 File creation opening and closing

2.1 Use the built-in functions open(), close() to create open and close

2.2 Use the with statement to open and close

2 Reading the file

2.1 Read the entire file read()

2.2 Read file content line by line readlines()

3 Writing to the file

3.1 Direct write

3.2 Write the entire file

3.3 Write to file line by line

4 Copy and delete files

4.1 File Copy

4.2 File deletion

5 Exception handling for basic file operations

6 Basic operation of files, complete example demonstration


Column guide 

Column subscription address: https://blog.csdn.net/qq_35831906/category_12375510.html


File operations are commonly used tasks in Python, and they allow us to efficiently work with text, data, and other types of files. Python provides a wealth of file operation functions, which can open, read, write, copy and delete files. Use the built-in open() function to open a file and specify a read or write mode. To read the file content, use the read() or readlines() function, and to write the file content, use the write() or writelines() function. The shutil module can be used to copy and move files, and the os module can be used to delete files.

1 File creation opening and closing

        Python provides many functions and methods for file operations, making operations such as reading, writing, copying, and moving files simple and efficient. To read, write, or otherwise operate on a file, you need to open the file and then close the file when you're done. When opening a file, you can use open()a function that takes a file path and an opening mode as parameters and returns a file object. When file operations are complete, close()the file object should be closed using the method to release resources.

2.1 Use the built-in functions open(), close() to create open and close

  1. Opening a file To open a file, use the built-in open() function. The open() function accepts two parameters: file name and open mode (such as read mode, write mode, etc.). Open modes include:
  • "r": read mode (default). Open the file for reading.
  • "w": write mode. Open the file for writing, or overwrite it if it already exists.
  • "a": append mode. Opens the file for writing, appending to the end of the file if it already exists.
  • "x": create mode. Create a new file and open it for writing, or throw an error if the file already exists.
  • "b": binary mode. Used to manipulate binary files.
  • "t": text mode (default). For manipulating text files.

Here is an example of opening and closing a file:

# 打开文件并写入内容
file_path = "example.txt"
file = open(file_path, "w")  # 使用写入模式打开文件

file.write("Hello, this is a new file!\n")
file.write("Welcome to Python file handling.\n")

file.close()  # 关闭文件

# 打开文件并读取内容
file = open(file_path, "r")  # 使用读取模式打开文件

content = file.read()
print("文件内容:")
print(content)

file.close()  # 关闭文件

In the above example, open()the function is first used to open the file in write mode and close the file after writing the content. Then use open()the function to open the same file again in read mode and close the file again after reading the file content.

2.2 Use the with statement to open and close

Note that to ensure proper release of file resources, it is best to use withthe open file statement so that even if an exception occurs, withthe file will be automatically closed after exiting the code block. The following are withexamples of usage statements:

file_path = "example.txt"
# 使用with语句打开文件
with open(file_path, "w") as file:
    file.write("Hello, this is a new file!\n")
    file.write("Welcome to Python file handling.\n")

# 使用with语句读取文件
with open(file_path, "r") as file:
    content = file.read()
    print("文件内容:")
    print(content)

2 Reading the file

2.1 Read the entire file read()

        Get the contents of the file You can use the read() method to read the contents of the file. The read() method reads the entire file as a string. 

Example:

file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

2.2 Read file content line by line readlines()

        Use the readlines() method to read the contents of the file line by line and store each line as an element in a table.

Example:

file = open("example.txt", "r")
lines = file.readlines()
for line in lines:
    print(line)
file.close()

3 Writing to the file

3.1 Direct write

        In Python, you can use write()the methods of the file object to write content to the file. A prerequisite for writing is that the file has been opened in write mode ("w") or append mode ("a"). The write mode will clear the contents of the file and write the new content, while the append mode will append the new content to the end of the file without clearing the original content.

Here is an example of file writing:

# 使用写入模式("w")打开文件
file_path = "example.txt"
file = open(file_path, "w")

# 向文件中写入内容
file.write("Hello, this is a new file!\n")
file.write("Welcome to Python file handling.\n")

# 关闭文件
file.close()

After running the above code, the content in the "example.txt" file will be overwritten as:

 If the file is opened in append mode ("a"), the new content will be appended to the end of the file without affecting the original content:

# 使用追加模式("a")打开文件
file_path = "example.txt"
file = open(file_path, "a")

# 向文件中追加内容
file.write("This is an additional line.\n")

# 关闭文件
file.close()

After running the above code, the contents of the "example.txt" file will become:

  It should be noted that when using file writing operations, make sure that the file has been opened in write mode or append mode, and close the file in time after writing is completed to release file resources. Also, to ensure that the file is closed properly, it is recommended to use withthe statement to open the file.

3.2 Write the entire file

To write the entire content to a file, you can open the file with the file open mode as "w"or "wb", and use write()the method to write the content to the file. If the file does not exist, a new file will be created and written; if the file already exists, the written content will overwrite the original content.

Example 1:

file_path = "example.txt"
content = "Hello, this is a new file!\nWelcome to Python file handling."

with open(file_path, "w") as file:
    file.write(content)

Result: example.txtwrites the following in the file:

In the example above, the entire content is contentwritten to the file at once example.txt.

3.3 Write to file line by line

        To write a file line by line, open the file with the file open mode as "w"or "wb"and use write()the method to write the content line by line. A newline character is added after each write \nto break the line.

Example 2:

file_path = "example.txt"
lines = ["Line 1", "Line 2", "Line 3"]

with open(file_path, "w") as file:
    for line in lines:
        file.write(line + "\n")

Result: example.txtwrites the following in the file:

  In the above example, linesthe content of each line in the list is written to the file line by line through a loop example.txt, and a newline character is added at the end of each line \nto achieve line-by-line writing.

It should be noted that when using file writing, make sure that the file opening mode is write mode "w"or append mode "a". At the same time, after using withthe statement to open the file, the file will be withautomatically closed when exiting the code block to ensure that the file resources are released correctly.

In example 1, when writing the entire content to the file, use write()the method to write the entire string to the file. In Example 2, when writing a file line by line, use fora loop to traverse the content of each line, and use write()the method to write the file line by line. A newline character is added after each write \nto ensure that each line of content occupies a separate line.

4 Copy and delete files

        You can use the shutil module in Python to copy and delete files.

4.1 File Copy

        To copy files, you can use the copy() function of the shutil module. The copy() function accepts two parameters: the source file name and the destination file name. It will copy the source file to the destination file and return the path of the destination file.

Example:

import shutil

# 源文件路径
source_file = "source.txt"
# 目标文件路径
destination_file = "destination.txt"

# 使用shutil模块的copyfile()函数进行文件复制
shutil.copyfile(source_file, destination_file)

print("文件复制成功!")

4.2 File deletion

        In Python, you can use the remove() function of the os module to delete files. The remove() function accepts one parameter, the path of the file to be removed. Here is sample code to delete a file:

import os

# 要删除的文件路径
file_to_delete = "file_to_delete.txt"

# 使用os模块的remove()函数删除文件
os.remove(file_to_delete)

print("文件删除成功!")

Note: When deleting files, please make sure that the files are unnecessary or the backup has been completed. File deletion is an irreversible operation, and files cannot be recovered after deletion. Therefore, it is prudent to confirm before deleting files. 

import os

# 定义要删除的文件路径
file_path = 'example.txt'

try:
    # 删除文件
    os.remove(file_path)
    print(f"文件 {file_path} 删除成功")
except FileNotFoundError:
    print(f"文件 {file_path} 不存在")
except Exception as e:
    print(f"删除文件时发生错误:{e}")

 In the above code, we first imported the os module. Then, the path to the file to delete is defined, i.e. 'example.txt'. Then use the try-except statement block to handle exceptions that may be caused by the file deletion operation. If the file exists and the deletion was successful, it will print "The file example.txt was deleted successfully". If the file does not exist, it will print "The file example.txt does not exist". If other errors occur while deleting files, the corresponding error messages are printed. Please note that before performing the delete operation, please ensure that you have sufficient permissions to perform the operation.

5 Exception handling for basic file operations

        When performing basic file operations, we need to pay attention to the exceptions that may be caused by file operations, such as file does not exist, file cannot be opened or read, file write failure, etc. In order to deal with these errors, we can use the exception handling mechanism to catch and handle these exceptions.

        In Python, we can use the try-except statement to implement exception handling. Execute file operations in the try code block. If an exception occurs, it will jump to the corresponding except code block for processing.

Here is an example of error handling for a basic file operation:

file_path = "example.txt"

try:
    # 打开文件以读取内容("r"表示读取模式)
    with open(file_path, "r") as file:
        content = file.read()
    print("文件内容:", content)

except FileNotFoundError:
    print("文件不存在,请确认文件路径是否正确。")

except IOError:
    print("文件读取失败,请检查文件是否可读。")

finally:
    print("文件操作完成。")

In the above example, we are trying to open a file and read its contents. If the file does not exist, a FileNotFoundError exception will be thrown; if the file cannot be read, an IOError exception will be thrown. File operations are performed in the try code block. If an exception occurs, it will jump to the corresponding except code block for processing. Finally, the code in the finally block executes whether or not an exception occurs. 

6 Basic operation of files, complete example demonstration

The following is a complete Python example that demonstrates the basic operations of files, including creating files, writing content, reading content, copying files, deleting files, and appending content.

def create_file(file_path):
    try:
        # 创建文件并写入内容
        with open(file_path, "w") as file:
            file.write("Hello, this is a new file!\n")
            file.write("Welcome to Python file handling.\n")
        print(f"文件 {file_path} 创建成功。")

    except IOError:
        print("文件创建失败。")

def read_file(file_path):
    try:
        # 打开文件以读取内容
        with open(file_path, "r") as file:
            content = file.read()
        print("文件内容:")
        print(content)

    except FileNotFoundError:
        print("文件不存在,请确认文件路径是否正确。")

    except IOError:
        print("文件读取失败,请检查文件是否可读。")

def copy_file(source_file, target_file):
    try:
        # 读取源文件内容
        with open(source_file, "r") as source:
            content = source.read()

        # 写入目标文件
        with open(target_file, "w") as target:
            target.write(content)

        print(f"文件 {source_file} 复制成功,保存为 {target_file}。")

    except FileNotFoundError:
        print("源文件不存在,请确认文件路径是否正确。")

    except IOError:
        print("文件复制失败。")

def append_file(file_path, content_to_append):
    try:
        # 在文件末尾追加内容
        with open(file_path, "a") as file:
            file.write(content_to_append + "\n")

        print("内容成功追加到文件。")

    except FileNotFoundError:
        print("文件不存在,请确认文件路径是否正确。")

    except IOError:
        print("文件追加失败。")

def delete_file(file_path):
    try:
        # 删除文件
        import os
        os.remove(file_path)
        print(f"文件 {file_path} 删除成功。")

    except FileNotFoundError:
        print("文件不存在,请确认文件路径是否正确。")

    except IOError:
        print("文件删除失败。")

if __name__ == "__main__":
    file_path = "example.txt"
    create_file(file_path)
    read_file(file_path)

    target_file = "example_copy.txt"
    copy_file(file_path, target_file)
    read_file(target_file)

    append_content = "This line is appended to the file."
    append_file(file_path, append_content)
    read_file(file_path)

    delete_file(file_path)

The result of the operation is as follows

Guess you like

Origin blog.csdn.net/qq_35831906/article/details/131955322