25

I'm trying to write a simple program to read a file and search for a word then print how many times that word is found in the file. Every time I type in "test.rtf" (which is the name of my document) I get this error:

Traceback (most recent call last):
  File "/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/How many? (Python).py", line 9, in <module>
    fileScan= open(fileName, 'r')  #Opens file
FileNotFoundError: [Errno 2] No such file or directory: 'test.rtf'

In class last semester, I remember my professor saying you have to save the file in a specific place? I'm not sure if he really said that though, but I'm running apple OSx if that helps.

Here's the important part of my code:

fileName= input("Please enter the name of the file you'd like to use.")
fileScan= open(fileName, 'r')  #Opens file
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 2
    since you don't give a path, the file should be in the directory where you run the script. probably `/Users/AshleyStallings/Documents/School Work/Computer Programming/` – njzk2 Jul 15 '13 at 16:17

8 Answers8

19

If the user does not pass the full path to the file (on Unix type systems this means a path that starts with a slash), the path is interpreted relatively to the current working directory. The current working directory usually is the directory in which you started the program. In your case, the file test.rtf must be in the same directory in which you execute the program.

You are obviously performing programming tasks in Python under Mac OS. There, I recommend to work in the terminal (on the command line), i.e. start the terminal, cd to the directory where your input file is located and start the Python script there using the command

$ python script.py

In order to make this work, the directory containing the python executable must be in the PATH, a so-called environment variable that contains directories that are automatically used for searching executables when you enter a command. You should make use of this, because it simplifies daily work greatly. That way, you can simply cd to the directory containing your Python script file and run it.

In any case, if your Python script file and your data input file are not in the same directory, you always have to specify either a relative path between them or you have to use an absolute path for one of them.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Dr. Jan-Philip Gehrcke
  • 33,287
  • 14
  • 85
  • 130
4

Is test.rtf located in the same directory you're in when you run this?

If not, you'll need to provide the full path to that file.

Suppose it's located in

/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/data

In that case you'd enter

data/test.rtf

as your file name

Or it could be in

/Users/AshleyStallings/Documents/School Work/Computer Programming/some_other_folder

In that case you'd enter

../some_other_folder/test.rtf

adhaamehab
  • 85
  • 5
Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
3

A good start would be validating the input. In other words, you can make sure that the user has indeed typed a correct path for a real existing file, like this:

import os
fileName = input("Please enter the name of the file you'd like to use.")
while not os.path.isfile(fileName):
    fileName = input("Whoops! No such file! Please enter the name of the file you'd like to use.")

This is with a little help from the built in module os, That is a part of the Standard Python Library.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
user1555863
  • 2,567
  • 6
  • 35
  • 50
  • 2
    FWIW, generally using a try-except is better practice, i.e. `try: open(fileName); except FileNotFoundError: print('Whoops! No such file!') ...` – wjandrea Jul 05 '20 at 18:30
3

As noted above the problem is in specifying the path to your file. The default path in OS X is your home directory (/Users/macbook represented by ~ in terminal ...you can change or rename the home directory with the advanced options in System Preferences > Users & Groups).

Or you can specify the path from the drive to your file in the filename:

path = "/Users/macbook/Documents/MyPython/"
myFile = path + fileName

You can also catch the File Not Found Error and give another response using try:

try:
    with open(filename) as f:
        sequences = pick_lines(f)
except FileNotFoundError:
    print("File not found. Check the path variable and filename")
    exit()
Spookpadda
  • 41
  • 3
1

You might need to change your path by:

import os
path=os.chdir(str('Here_should_be_the_path_to_your_file')) #This command changes directory

This is what worked for me at least! Hope it works for you too!

RandML000
  • 11
  • 1
  • 4
0

Difficult to give code examples in the comments.

To read the words in the file, you can read the contents of the file, which gets you a string - this is what you were doing before, with the read() method - and then use split() to get the individual words. Split breaks up a String on the delimiter provided, or on whitespace by default. For example,

"the quick brown fox".split()

produces

['the', 'quick', 'brown', 'fox']

Similarly,

fileScan.read().split()

will give you an array of Strings. Hope that helps!

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
0

First check what's your file format(e.g: .txt, .json, .csv etc ),

If your file present in PWD , then just give the name of the file along with the file format inside either single('')or double("") quote and the appropriate operation mode as your requirement

e.g:

with open('test.txt','r') as f: data=f.readlines() for i in data: print(i) If your file present in other directory, then just give the full path name where is your file is present and file name along with file format of the file inside either single('')or double("") quote and the appropriate operation mode as your requirement.

If it showing unicode error just put either r before quote of file path or else put '/' instead of ''

with open(r'C:\Users\soman\Desktop\test.txt','r') as f: data=f.readlines() for i in data: print(i)

-1

The mistake I did was my code :

x = open('python.txt')

print(x)

But the problem was in file directory ,I saved it as python.txt instead of just python .

So my file path was ->C:\Users\noob\Desktop\Python\Course 2\python.txt.txt

That is why it was giving a error.

Name your file without .txt it will run.

Jamiu S.
  • 5,257
  • 5
  • 12
  • 34
noob
  • 1