为什么当打开模式为“ w'??

发布于 2025-02-06 17:49:15 字数 326 浏览 1 评论 0原文

我正在遵循一个教程,该教程创建一个函数来创建20个TXT文件,并在其中添加1到20个乘法表。这是代码 -

#Create tables from 1 to 20 in different files 

for i in range(1,21):
    with open(f"table_{i}.txt","w") as f:
        for j in range(1,11):
            f.write(f"{i} x {j} = {i*j}\n")

此代码可以完成作业,但我不确定为什么它会附加到文件上,而不是在“ W”/写作模式打开时覆盖它?

I was following a tutorial that creates a function to create 20 txt files and add the multiplication tables from 1 to 20 in them. Here is the code-

#Create tables from 1 to 20 in different files 

for i in range(1,21):
    with open(f"table_{i}.txt","w") as f:
        for j in range(1,11):
            f.write(f"{i} x {j} = {i*j}\n")

This code does the job but I am not sure why does it append to the file and not overwrite it when it is open in "w"/writing mode?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的他你的她 2025-02-13 17:49:15

是的,当您使用“ W”时,您是对的,然后覆盖并没有附加,但是在这里不是附加。
当您再次打开文件时,附加和覆盖的概念就会发挥作用,但是在这里我们不是再次打开文件,而只是在打开的文件中写入。
让我通过一个示例解释:

for i in range(1,21):
    for j in range(1,11):
        with open(f"table_{i}.txt","w") as f:
            f.write(f"{i} x {j} = {i*j}\n")

尝试运行此代码,它将像以前一样为您提供20个文件我们将在每行之后打开文件,以便每次打开时,'w'覆盖旧数据。

希望它有帮助:)

Yes, you are right when you use 'w' then it overwrites and does not append but here it is not appending.
The concept of appending and overwriting comes into play when you open the file again but here we are not opening the file again but just writing in the opened file.
Let me explain by an example:

for i in range(1,21):
    for j in range(1,11):
        with open(f"table_{i}.txt","w") as f:
            f.write(f"{i} x {j} = {i*j}\n")

try to run this code, it will give you 20 files as before but this time every file just had just a single column say 10 x 10 = 100 like this only because here we are opening the file after every line so every time we open, 'w' overwrites the old data.

Hope it helps:)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文