Python 3中readline调用异常,无法正确读取文本文件行内容
Why Your Output Doesn't Match the File Content & How to Fix It
Hey, let's break down why your code is producing those weird fragmented outputs instead of your actual file lines—you've got a couple of key misunderstandings about how Python's file reading methods work.
The Core Issues
- Misusing
readline()parameters: When you doline(2)orline(3), you're not asking for the 2nd or 3rd line. The number you pass toreadline(n)tells Python to read up to n bytes from the current file position, not the nth full line. That's why you're getting those random short chunks. - File pointer movement: Every call to
readline()moves the file pointer forward. After reading the first line withline(), subsequent calls start from where the last one left off, not the start of the file. - Minor syntax quirk: While
line = f.readline(without parentheses) lets you callline()to read a line, it's not necessary—you can just usef.readline()directly, but this isn't the main problem.
Fixed Code Examples
Let's adjust your code to properly read and print each line as expected. Here are a few solid options:
Option 1: Most Pythonic & Efficient (Iterate Directly Over the File)
This method reads lines one at a time without loading the entire file into memory (great for large files):
import sys accFiletypes = '.txt' correctFiletype = False while not correctFiletype: filnavn = input("Filename (Type exit to leave):") if filnavn.endswith(accFiletypes): try: # Use a `with` statement to auto-close the file (safer!) with open(filnavn, 'r') as f: correctFiletype = True print("File successfully opened!") # Iterate over each line in the file for line in f: # Use strip() to remove trailing newlines, or omit to keep them print(line.strip()) except IOError: print("File does not exist") elif filnavn == "exit": sys.exit("Program closed") else: print(f"Accepted filetypes: {accFiletypes}")
Option 2: Load All Lines Into a List (For Specific Line Access)
If you need to access lines by their number (like your original attempt to print the first 6 lines), use readlines():
# Inside the try block (replace the for loop from Option 1): with open(filnavn, 'r') as f: correctFiletype = True print("File successfully opened!") lines = f.readlines() # Print the first 6 lines (indexes 0 to 5) for i in range(6): print(lines[i].strip())
Option 3: Track Line Numbers With enumerate()
Use this if you want to print line numbers alongside the content:
# Inside the try block: with open(filnavn, 'r') as f: correctFiletype = True print("File successfully opened!") for line_num, line in enumerate(f, start=1): print(f"Line {line_num}: {line.strip()}") # Stop after 6 lines if needed if line_num == 6: break
Key Takeaways
file.readline()(no arguments) reads one full line;file.readline(n)reads up tonbytes, not the nth line.- Using a
withstatement is always recommended for file handling—it automatically closes the file even if an error occurs. - Iterating directly over the file object (
for line in f) is the most efficient way to read lines for most use cases.
内容的提问来源于stack exchange,提问作者M3ME5
相关产品推荐
相关产品推荐

