2

I am trying to open a txt file for reading with this code:-

type_comments = [] #Declare an empty list
with open ('society6comments.txt', 'rt') as in_file:  #Open file for reading of text data.
 for line in in_file: #For each line of text store in a string variable named "line", and
   type_comments.append(line.rstrip('\n'))  #add that line to our list of lines.

Error:-

Error  - Traceback (most recent call last):
  File "c:/Users/sultan/python/society6/society6_promotion.py", line 6, in <module>
    with open ('society6comments.txt', 'rt') as in_file:
FileNotFoundError: [Errno 2] No such file or directory: 'society6comments.txt'

I already have a file name with 'society6comments.txt' in the same directory has my script so why is it showing error?

enter image description here

Sultan Morbiwala
  • 171
  • 1
  • 3
  • 15
  • Give it the full path, just to see what happens – SuperStew Sep 19 '18 at 14:01
  • 2
    Possible duplicate of [FileNotFoundError: \[Errno 2\] No such file or directory](https://stackoverflow.com/questions/22282760/filenotfounderror-errno-2-no-such-file-or-directory) – Sheldore Sep 19 '18 at 14:02
  • Another similar question asked [here](https://stackoverflow.com/questions/48200441/filenotfounderror-while-opening-file-in-python) – Sheldore Sep 19 '18 at 14:03

2 Answers2

2

The fact that the text file is in the same directory as your program does not make that directory the current working directory. Put the full path to the file in your open() call.

BoarGules
  • 16,440
  • 2
  • 27
  • 44
  • 3
    When is the directory your py file is in not the working dir? – SuperStew Sep 19 '18 at 14:02
  • 2
    @SuperStew whenever you run the script from another place, whenever anything in the chain (for example a badly written module you import in your script) changes the working dir, and I'm not even talking about what can happen when your "py file" is used as a module instead of a script. – bruno desthuilliers Sep 19 '18 at 14:12
  • Interesting. Somehow I haven't run into that issue yet. good to know though – SuperStew Sep 19 '18 at 14:17
0

You can use os.path.dirname(__file__) to obtain the directory name of the script, and then join the file name you want:

import os
with open (os.path.join(os.path.dirname(os.path.abspath(__file__)), 'society6comments.txt'), 'rt') as in_file:
blhsing
  • 91,368
  • 6
  • 71
  • 106