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


浙公网安备 33010602011771号