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
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
GitHub - BLACKxZONE/Treasure_knowledgehttps://github.com/BLACKxZONE/Treasure_knowledge