0

For some reason despite having the file in the main and in the same directory, I keep getting the no such file error. Any help is appreciated.

    import time
    def firstQues():

            print('"TT(Announcing): HONING IN FROM SU CASA CUIDAD, (Their hometown)"')
            time.sleep(3)
            print('"VEN EL UN.....(Comes the one.....)"')
            time.sleep(2)
            print('"EL SOLO......(The ONLY.....)"')
            time.sleep(3)
            print('"Campeón NOVATO (NEWBIE CHAMP)"')
            print()


            text_file = open("Questions1.txt", "r")
            wholefile = text_file.readline()
            for wholefile in open("Questions1.txt"):
                    print(wholefile)
                    return wholefile
                    return text_file

    def main():
            firstQues()
            text_file = open("Questions1.txt", "r")
    main()

3 Answers3

0

You cannot open a file in read mode that doesn't exist. Make sure you create a file in a current working directory. Your program executed successfully.

enter image description here

rsirs
  • 107
  • 7
  • Ok thanks, it's in the correct directory but now it's only reading one line of the file when I changed text_file.readline() to text_file.read() – James Diego Tao Sep 28 '16 at 04:58
0
  with open("Questions1.txt", "r") as f:
       file_data = f.read().splitlines()
  for line in file_data:
      #do what ever you want 

How do I read a file line-by-line into a list?

Community
  • 1
  • 1
rsirs
  • 107
  • 7
0

The simplest solution comes down to a paradigm choice, ask for permission or ask for forgiveness.

Ask for permission: check if the file exists before using

import os.path

if os.path.isfile("Questions1.txt"):
  #read file here

Ask for forgiveness: try-except block, report if issues

try:
  #read file and work on it
except:
  print 'Error reading file'

If you use read-write flag, it will create a file when it doesn't exist, but it doesn't seem like you want to write

with open("Questions1.txt", "rw") as f:
  #work on file

Pick your poison. Hope this helps :)

Lekic
  • 39
  • 5