【问题标题】:File creation problem in python, receiving unexpected outputpython中的文件创建问题,收到意外的输出
【发布时间】: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()

标签: python file-io


【解决方案1】:

这段代码做了它应该做的事:

for all names in your directory:
   if name is 'abc.txt':
       program prints your message
   in other case:
       you opens the file 'abc.txt' and writes 10000 lines
       then you opens it again and reads first 10 lines

Python 是缩进依赖语言,请确保正确使用它们。

【讨论】:

    【解决方案2】:

    是的,我找到了我的解决方案,谢谢大家。

    import os 
    
    filenames = os.listdir()
            for names in filenames:
                if names == "abc.txt":
                    print("FIle Exists, Please Remove Old File And Try Again")
                    break
            else:
                with open("abc","w") as file:
                    file.write("abcde\n"*10000)
                with open("abc.txt") as file:
                    print(file.read(10))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      • 2022-08-05
      • 1970-01-01
      相关资源
      最近更新 更多