python 中 文件读取循环的坑
001、
[root@pc1 test3]# ls a.txt b.txt test.py [root@pc1 test3]# cat a.txt 1 2 3 [root@pc1 test3]# cat b.txt 1 2 3 [root@pc1 test3]# cat test.py ## 测试程序 in_file = open("a.txt", "r") out_file = open("b.txt", "r") for i in in_file: for j in out_file: print("xx") [root@pc1 test3]# python test.py ## 只输出了3次 ; 应为out_file是文件,只打开一次 xx xx xx
002、
[root@pc1 test3]# cat b.txt 1 2 3 [root@pc1 test3]# cat test.py ## 改进代码,将out_file保存至列表中 in_file = open("a.txt", "r") out_file = open("b.txt", "r") tmp = out_file.readlines() for i in in_file: for j in tmp: print("xx") [root@pc1 test3]# python test.py ## 输出9此循环 xx xx xx xx xx xx xx xx xx
分类:
python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2021-11-03 R语言中如何将数据从矩阵转换为3列的形式
2021-11-03 R语言中如何统计数据框中某一个元素出现的次数
2021-11-03 plink + R构建G矩阵
2020-11-03 linux系统中配置sshd服务(远程控制服务)
2020-11-03 帧数、帧率(FPS)是什么?
2020-11-03 linux虚拟机如何连接外网
2020-11-03 linux虚拟机如何配置网卡信息(确保两台服务器通信)