2

I keep getting errors, that the file doesn't exist. This is the first time im doing this and cant find a sufficient answer on google.

the file is stored in a folder with the name : "maths", the documents name is "Data.txt"

the code ive written to read the content is:

def read(data):
    try:
        count=0
        INFILE=open("maths\\Data.txt","r")
        for line in INFILE:
            rawdata.append(line.rstrip())
            count+=1
        INFILE.close()
        return count
    except:
        print("File could not be found")
        return(count)
        exit()
  • The file path must be specified relative to from where you run the script. – mkrieger1 Jun 06 '20 at 15:03
  • 1
    Can you post the error without the error handler? – Red Jun 06 '20 at 15:04
  • Big +1 to @AnnZen. The code has a lot of lines in a catch-all `try`... `except`, and it could be hiding a lot of different potential sources of error. It is a bad idea to use exception handling in this way; one should catch the specific exception relating to expected error conditions only (e.g. `except OSError:`). – alani Jun 06 '20 at 15:07
  • thats the error –  Jun 06 '20 at 15:08
  • As you're using a relative path, it might be worth doing `print(os.getcwd())` to check what current directory the script is using (you'll need to `import os`). – alani Jun 06 '20 at 15:13

1 Answers1

1

One sure fire way is to list the whole path of the text file.

Assuming the folder is in Desktop, and the User name of you pc is User1:

def read(data):
    try:
        count=0
        INFILE=open("C:\\Users\\User1\\Usermaths\\Data.txt","r")
        for line in INFILE:
            rawdata.append(line.rstrip())
            count+=1
        INFILE.close()
        return count
    except Exception as e:
        print(e)
        return(count)
        exit()
Red
  • 26,798
  • 7
  • 36
  • 58