【问题标题】:Why aren't the contents of my text file printing in python?为什么我的文本文件的内容不在 python 中打印?
【发布时间】:2021-11-16 19:36:17
【问题描述】:

我在更改文件内容后尝试打开文件。更改内容后,文件将无法打开,也不会产生输出。

first part of code

second part of code where issues are occuring

【问题讨论】:

  • 请将代码包含为带格式的文本(使用`将其格式化为代码)
  • 您永远不会向文件写入任何内容。它打开得很好,但里面没有任何东西可以阅读和打印

标签: python printing


【解决方案1】:

提示(因为这显然是家庭作业):而不是

   ...
   print(x)

你怎么能write到文件fnumbers

【讨论】:

    【解决方案2】:

    你忘记使用问题 4 中的 write 方法,因此问题 5 中没有要读取的数据

    fnumbers = open("cube_numbers.txt", "w")
    for num in range(1,20):
        if num % 2 != 0:
            x = num ** 3
            fnumbers.write(str(x) + "\n" )
    fnumbers.close()
    

    回答第5题,先用read方法打开文件,用for循环简单

    fnumbers = open("cube_numbers.txt", "r")
    sum = 0;
    
    for num in fnumbers:
        number = int(num)
        if(number % 3 == 0):
            print(number)
            sum = sum + number
    print("sum = ", sum)
    fnumbers.close()
    
    
    
        
         
    

    【讨论】:

      猜你喜欢
      • 2015-08-11
      • 2019-11-19
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      相关资源
      最近更新 更多