0

I'm new at learning python and i don't know which default directory python use to open file.

I have read some of the similar question answer on stackoverflow but didn't helped me. I'm running python 3.6.2.

I have following code where 'test.txt' file is stored where all .py files stored but i'm getting

FileNotFoundError: [Errono 2] No such file or directory: 'test.txt'

handle = open('test.txt')
for line in handle:
   print(line)
user2722968
  • 13,636
  • 2
  • 46
  • 67
Jay
  • 53
  • 2
  • 8
  • Thanks!! suppose i have 100s of files in /home/jay/config directory and i have .py files in /home/jay directory. How can i open all files and search pattern ? I tried following and got the error: ` import re` `import os` `os.chdir(r'/home/juniper/configs/')` `files = open('*')` `for line in files :` `line = line.rstrip()` ` if re.search('Model' , line):` `print(line)` Traceback (most recent call last): File "/home/juniper/test.py", line 4, in ? files = open('*') IOError: [Errno 2] No such file or directory: '*' – Jay Jul 25 '17 at 21:06

3 Answers3

0

Same directory / relative Location: How to refer to relative paths of resources when working with a code repository in Python

Any directory: Just give the absolut path to open() function (e.g. inenter link description here)

Freddy
  • 156
  • 1
  • 8
0

Modules have a __file__ attribute that points to the full path and filename the module is loaded from. You can use the pathlib-module to extract the path (cutting the .py-filename) and construct a new full pathname.

import mymodule

with open(pathlib.path(mymodule.__file__).parent / 'test.txt') as f:
    for line in f:
        print(line)

That way wherever mymodule is loaded from test.txt will be opened from.

user2722968
  • 13,636
  • 2
  • 46
  • 67
0

i'm using linux if i want to open a file in a different location than my current working directory i would have done this

myfile = open('/user/path/file')

example

myfile = open('/root/Desktop/css/base.css', 'r')

  • I tried this ' handle = open('C:\Users\jay\Documents\Python Code\test') ' and gave me same error. I'm using windows. – Jay Jul 24 '17 at 14:59
  • suppose i have 100s of files in /home/jay/config directory and i have .py files in /home/jay directory. How can i open all files and search pattern ? I tried following and got the error: ` import re` `import os` `os.chdir(r'/home/juniper/configs/')` `files = open('*')` `for line in files : ` `line = line.rstrip() ` `if re.search('Model' , line):` `print(line)` **Following is the error** `Traceback (most recent call last): File "/home/juniper/test.py", line 4, in ? files = open('') IOError: [Errno 2] No such file or directory: '' ` – Jay Jul 26 '17 at 13:12