Reputation: 25
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.
Upvotes: 0
Views: 92
Reputation: 136
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)
Upvotes: 0
Reputation: 2068
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")
Upvotes: 3