简体   繁体   English

为什么我的文本文件的内容不在 python 中打印?

[英]Why aren't the contents of my text file printing in python?

I am trying to open a file after I have changed the contents of it.我试图在更改文件内容后打开文件。 After I changed the contents, the file will not open and will not produce an output.更改内容后,文件将无法打开,也不会产生输出。

first part of code第一部分代码

second part of code where issues are occuring发生问题的代码的第二部分

HINT (as this is clearly homework): instead of提示(因为这显然是家庭作业):而不是

   ...
   print(x)

how might you write to the file fnumbers ?你如何write文件fnumbers

You forgot to use the write method in Question 4, hence that is why there is no data to be read in Question 5你在问题 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()

To answer Question 5, first open the file with read method and simply use for loop要回答问题 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()



    
     

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM