简体   繁体   中英

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 ?

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

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()



    
     

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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