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

使用Python循环生成2至20的乘法表并写入独立文件时的代码执行异常问题求解

Why does the first code only write the last line of the multiplication table?

Let's break down exactly why these two snippets behave so differently—it all comes down to when you're opening the file and how Python's 'w' write mode works.

The problem with your first code

In your first snippet, you're putting the with open(...) call inside the inner j loop:

for i in range(2, 21):
    for j in range(1, 11):
        with open(f"tables/Multiplication_table_of_{i}.txt", 'w') as f:
            f.write(f"{i}X{j}={i*j}")
            if j!=10:
                f.write('\n')

Here's what happens step-by-step for a single i (say, i=2):

  • When j=1: You open Multiplication_table_of_2.txt in 'w' mode. This mode erases all existing content in the file (or creates it if it doesn't exist) before writing. You write 2X1=2 and a newline, then close the file.
  • When j=2: You open the same file again in 'w' mode. This erases the 2X1=2 line you just wrote, writes 2X2=4 and a newline, then closes.
  • This repeats for every j from 1 to 9.
  • Finally, when j=10: You open the file one last time, erase all previous content, write 2X10=20, and close.

By the time the inner loop finishes, the file only contains the last line you wrote—every prior line was overwritten when you reopened the file.

Why the second code works

Your second snippet moves the with open(...) call outside the inner j loop, into the outer i loop:

for i in range(2, 21):
    with open(f"tables/Multiplication_table_of_{i}.txt", 'w') as f:
        for j in range(1, 11):
            f.write(f"{i}X{j}={i*j}")
            if j!=10:
                f.write('\n')

Now, here's the flow for i=2:

  • You open Multiplication_table_of_2.txt once in 'w' mode (erasing any old content, or creating it). The file stays open for the entire duration of the inner j loop.
  • For each j from 1 to 10, you write the line directly to the open file. Since the file isn't being closed and reopened, each new line is added to the end of the file instead of overwriting it.
  • After all j values are processed, you close the file—now it contains all 10 lines of the multiplication table.

Key takeaway

The 'w' write mode in Python doesn't append to files—it replaces their content entirely every time you open them. To build up a file line by line, you need to either:

  • Open the file once and write all content before closing it (like your second snippet), or
  • Use the append mode 'a' instead of 'w' (though this isn't ideal here, since you'd end up with duplicate content if you rerun the code).

内容的提问来源于stack exchange,提问作者Preetish Kumar Nayak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 17:42:49