[Network security takes you to practice reptiles-100 exercises] Practice 14: Reading and taking out file content

Table of contents

1. Goal 1: Take out the content of the file through traversal

2. Goal 2: Take out all the contents of the file

3. Network Security


1. Goal 1: Take out the content of the file through traversal

 (1) If the file scripts are in different directories

file_path = "path/to/your/file.txt"  # 替换为你的文件路径
with open(file_path, "r") as file:
    # 逐行读取文件内容
    for line in file:
        # 处理每一行内容
        print(line)

(2) If the file is directly in the same directory as the script

with open(file.txt, "r") as file:
    # 逐行读取文件内容
    for line in file:
        # 处理每一行内容
        print(line)



2. Goal 2: Take out all the contents of the file

 (1) Store the retrieved elements

lines = []

(2) Take out the elements of the target file content in sequence

(for loop)

    with open('test.csv', 'r', encoding='utf-8') as file:
        for line in file:

(3) All elements are added to the list in turn

lines.append(line.strip())

(4) Complete code:

if __name__ == '__main__':
    lines = []
    with open('test.csv', 'r', encoding='utf-8') as file:
        for line in file:
            lines.append(line.strip())
            print(lines)
    print(lines[1])

(4) Method 2:

Read the contents of the file into a list using the readlines() method

with open(file_path, "r") as file:
    lines = file.readlines()
    # 循环遍历列表并处理每一行内容
    for line in lines:
        # 处理每一行内容
        print(line)


(5) Running results

3. Network Security

README.md Book Bansheng/Network Security Knowledge System-Practice Center-Code Cloud-Open Source China (gitee.com) https://gitee.com/shubansheng/Treasure_knowledge/blob/master/README.md

GitHub - BLACKxZONE/Treasure_knowledgehttps://github.com/BLACKxZONE/Treasure_knowledge

Guess you like

Origin blog.csdn.net/qq_53079406/article/details/131744170