0

Beginner to python here.

I am writing a program that involves opening and reading input from another file. The python file is called paint.py, while my input file is paint_test.in

fn = open('paint_test.in', 'r')

Whenever I try running that code, it gives me a "No file or directory error". The full path to my folder containing both these files: C:\Users\ayush\Desktop\USACO\paint

I would appreciate it if anyone could point me in the right direction here. Thanks!

  • try something like this open('C:/Users/ayush/Desktop/USACO/paint/paint_test.in', 'r') – SahilDesai May 22 '20 at 16:46
  • 1
    First at all try to list all files in your current directory to get sure that `pain_test.in` is actually in the same directory. To list all files in the current directory, see the following thread: https://stackoverflow.com/questions/11968976/list-files-only-in-the-current-directory – Code Pope May 22 '20 at 16:47
  • 1
    The file is not found because it is looking in the current directory, and the current directory isn't what you think it is. Depending on how you run Python, the current directory might be where the python program itself lives, not where your script lives. – John Gordon May 22 '20 at 16:50

2 Answers2

2

The file is not found because it is looking in the current directory, which is not the same directory where your script lives.

Depending on how you run Python, the current directory might be where the python executable program itself lives, or some other generic directory such as C:\.

One way around this problem is to use the full directory path to the filename:

fn = open('C:/Users/ayush/Desktop/USACO/paint/paint_test.in', 'r')

(Yes, forward slashes will work, and they're safer than backslashes, because you don't have to worry about certain combinations such as \n or \b being interpreted in a special way.)

John Gordon
  • 29,573
  • 7
  • 33
  • 58
1

That should not cause an error. Maybe you could try this giving an absolute path:

fn = open('C:\Users\ayush\Desktop\USACO\paint\paint_test.in', 'r')
rdas
  • 20,604
  • 6
  • 33
  • 46
Pratik Joshi
  • 389
  • 4
  • 13