Python 3 readline not working
本问题已经有最佳答案,请猛点这里访问。
你好,所以我想从文本文件中读取行。我的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import sys accFiletypes = '.txt' f = None filnavn = None correctFiletype = False while (correctFiletype == False): filnavn = input("Filename (Type exit to leave):") if (filnavn.endswith(accFiletypes) == True): try: f = open(filnavn, 'r') correctFiletype = True print("File successfully opened!") except IOError: print("File is not existing") elif (filnavn =="exit"): sys.exit("Program closed") else: print("Accepted filetypes:" + accFiletypes) line = f.readline print(line()) print(line(2)) print(line(3)) print(line(4)) print(line(5)) print(line(6)) f.close() |
打印以下内容:
1 2 3 4 5 6 7 8 9 10 | Filename (Type exit to leave):test.txt File successfully opened! 0000 00000000 00 00 0000 1 0000 0 |
"test.txt"中的前10行
1 2 3 4 5 6 7 8 9 10 | 0000 00000000 0000 00001 0000 00001111 0000 000099 0000 00009999 0000 0000w 0000 5927499 0000 634252 0000 6911703 0000 701068 |
我希望它打印出TXT文件中的行,但我打印的内容完全不同。我该怎么办?
据我所知,
1 2 3 4 5 6 7 8 9 10 | print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) print(f.readline()) |
不过,我建议与处理关闭流的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import sys accFiletypes = '.txt' def parse_file(f): with open(f, 'r') as fin: for line in fin: print(line) correctFiletype = False while (correctFiletype == False): filnavn = input("Filename (Type exit to leave):") if filnavn.endswith(accFiletypes): try: parse_file(filnavn) correctFiletype = True print("File successfully opened!") except IOError: print("File is not existing") elif filnavn =="exit": sys.exit("Program closed") else: print("Accepted filetypes:" + accFiletypes) |
我想你的意思是:
1 2 3 4 | for line in f: print(line) f.close() |
或者,如果你想读前六行,你可以这样做:
1 2 3 | line = f.readline for _ in range(6): print(line()) |
注意,