-2

I have tried to get my program to open but it keeps saying FileNotFound

def main():
   with open("number.txt") as f:
       nums=[int(x) for x in f.read().split()]
   print(nums)
   for nums in nums:
       total += int(nums)
   print(total) 
   print(len(nums))
   return total / len(nums)
main()
Klaus D.
  • 13,874
  • 5
  • 41
  • 48

2 Answers2

0

Python will look for "number.txt" in your current directory which by default is the same folder that your code started running in. You can get the current directory by using os.getcwd() and if that for some reason is not what you expect, you can also get the directory to the folder that your code is running in by doing current_directory = os.path.dirname(os.path.realpath(__file__)).

The following code should always work, if you want your "number.txt" to be in the same folder as your code.

import os.path

def main():
    current_directory = os.path.dirname(os.path.realpath(__file__))
    filepath = os.path.join(current_directory, "number.txt")

    # Optionally use this to create the file if it does not exist
    if not os.path.exists(filepath):
        open(filepath, 'w').close()

    with open( filepath ) as f:
        ...
hostingutilities.com
  • 8,894
  • 3
  • 41
  • 51
0

Is number.txt in your working directory? If not you'd have to specify the path to that file so python knows where to look

T0r0nt0
  • 97
  • 9