0

I need to read the file called, "ranks.dat", however whenever I try opening the file it says there is no such file or directory even though I have downloaded the file. Below is my code:

# Reading from a file numFile = open("ranks.dat", "r") while True: text = numFile.readline() #rstrip removes the newline character read at the end of the line text = text.rstrip("\n") if text=="": break print (text, end = "\t") numFile.close() 

The files should always have the following fields: Rank - Word of Size 15 or less - the Name of the Card Power - Integer less than 100 - the Power of the Card Number - Integer less than 100 - the Number of these cards

I need to store each of the fields into their own list. But it does not seem to work.

4
  • 3
    I think your program is working as it should. You just need to make the file ranks.dat available to the program. Try copying it to the same folder as your script. Commented Jun 1, 2020 at 17:25
  • 5
    Is the file in the same directory as the script? If not, you need to provide a full path Commented Jun 1, 2020 at 17:25
  • @Dallan I am not sure how to put the file in the same directory as the script? Commented Jun 1, 2020 at 17:28
  • @quamrana How would I do that? Commented Jun 1, 2020 at 17:28

2 Answers 2

3

You need to specify the route, here are the lines.

import sys import os ROOT_DIR = os.path.dirname(os.path.realpath(__file__)) dir = os.path.join(ROOT_DIR, "YOURFOLDERNAME") numFile = open(dir+'/'+"ranks.dat", "r") 
Sign up to request clarification or add additional context in comments.

7 Comments

If the route is the same as the python file's, it is not necessary.
@AnnZen so I don't need those two lines?
That' s true, but maybe have problems with the path, apparently I think he can't find the file and has it inside another folder.
@kittykat0057 Is your two files in the same folder?
@AnnZen No, should I put it in the same folder and then try running it?
|
0

First make sure that Python is able to read the path to your file.

from os import path if path.exists('ranks.dat'): # do the file processing else: print('Filepath does not exist.') 

If it prints out that the file path does not exist, then you can provide the full filepath to ranks.dat and it should work.

In addition, you can also use a context manager to open and close the file for you when you are done

with open('ranks.dat', 'r') as f: for line in f.readlines(): print(line) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.