You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Misusing readline() parameters: When you do line(2) or line(3), you're not asking for the 2nd or 3rd line. The number you pass to readline(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.
  2. File pointer movement: Every call to readline() moves the file pointer forward. After reading the first line with line(), subsequent calls start from where the last one left off, not the start of the file.
  3. Minor syntax quirk: While line = f.readline (without parentheses) lets you call line() to read a line, it's not necessary—you can just use f.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 to n bytes, not the nth line.
  • Using a with statement 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:28:57