目录
一、目标1:把文件内容遍历取出
二、目标2:把文件内容全部取出
三、网络安全O
一、目标1:把文件内容遍历取出
(1)如果文件脚本在不同目录
file_path = "path/to/your/file.txt" # 替换为你的文件路径 with open(file_path, "r") as file: # 逐行读取文件内容 for line in file: # 处理每一行内容 print(line)
(2)如果文件直接和脚本在同一目录
with open(file.txt, "r") as file: # 逐行读取文件内容 for line in file: # 处理每一行内容 print(line)
二、目标2:把文件内容全部取出
(1)存放取出的元素
lines = []
(2)将目标文件内容的元素依次取出
(for循环)
with open('test.csv', 'r', encoding='utf-8') as file: for line in file:
(3)所有元素依次添加进列表中
lines.append(line.strip())
(4)完整代码:
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)方法二:
使用readlines()方法将文件内容读取到列表中
with open(file_path, "r") as file: lines = file.readlines() # 循环遍历列表并处理每一行内容 for line in lines: # 处理每一行内容 print(line)
(5)运行结果
三、网络安全O
README.md · 书半生/网络安全知识体系-实战中心 - 码云 - 开源中国 (gitee.com)https://gitee.com/shubansheng/Treasure_knowledge/blob/master/README.md
GitHub - BLACKxZONE/Treasure_knowledgehttps://github.com/BLACKxZONE/Treasure_knowledge