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

Python读取文件后内容消失问题及文件数字求和代码咨询

解答你的两个问题

Hey there! Let's break down your two questions one by one—first the file content "disappearing" mystery, then polishing up your number sum calculation code.

一、为什么Python读取文件后内容会"消失"?

This is all about the file pointer! When you iterate through a file with something like for line in f, the pointer starts at the beginning of the file and moves forward as it reads each line. By the time you finish the loop, the pointer is sitting at the very end of the file. If you try to read the file again without resetting it, there's nothing left to read from that position.

Fixes for this:

  • Reopen the file: Close the current file handle and call open() again to start fresh
  • Reset the pointer: Use f.seek(0) to move the pointer back to the start of the file

That said, the safest way to handle files in Python is using a with statement (we'll use this in the code below)—it automatically takes care of opening and closing the file, so you don't have to worry about pointer mishaps or forgotten close() calls.

二、完善数字总和计算的代码

Your core logic is already solid! You just need to fix a tiny typo and tweak the file handling for better practice. Here's the revised, fully working code:

import sys
import re

if len(sys.argv) != 2:
    print("Need exactly 1 parameter (use 'sample' for the test file)!")
    sys.exit(2)
# Exit codes:
# 2 = command line argument error
# 0 = normal exit
# 1 = other errors

# Set the correct file path based on input
if sys.argv[1] == "sample":
    file_path = "regex_sum_42.txt"
else:
    file_path = "regex_sum_89382.txt"

total = 0
# Use with statement to auto-manage the file
with open(file_path, "r") as f:
    for line in f:
        # Extract all numeric strings from the line
        line_numbers = re.findall(r"\d+", line)
        # Convert to integers and add to total
        total += sum(int(num) for num in line_numbers)

# Print the final total
print(f"Total sum of all numbers in the file: {total}")

Quick notes on the improvements:

  • with statement: Ensures the file is closed properly even if an error occurs, preventing resource leaks
  • Cleaner file path handling: Storing the path in a variable makes the code easier to read and modify
  • Simpler regex: r"\d+" does the same thing as "[0-9]+" but is more concise
  • Generator expression: int(num) for num in line_numbers uses less memory than a list comprehension, which is helpful for large files
  • Fixed typo: Changed the incomplete prin... to a full print() statement

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:52:06