【发布时间】:2020-09-18 07:58:10
【问题描述】:
所以一开始我在我的密码中搜索文件名,然后如果名称匹配,它将打印文件存在,但我不明白为什么我会收到这样的输出。
import os
filenames = os.listdir()
for names in filenames:
if names == "abc.txt":
print("FIle Exists, Please Remove Old File And Try Again")
else:
with open("abc.txt","w") as file:
file.write("abcde\n"*10000)
with open("abc.txt") as file:
print(file.read(10))
输出:
abcde
FIle Exists, Please Remove Old File And Try Again
abcde
abcde
abcde
abcde
abcde
abcde
abcde
【问题讨论】:
-
你期望的输出是什么?
-
当您的循环到达另一个未命名为
abc.txt的文件时,它会转到else:块并覆盖abc.txt文件。 -
在打开文件进行读取之前,您应该关闭正在写入的文件或使用
file.flush()。