0

The code is unable to read the txt file after importing the class in another python file gives file not found error code is something as followed:

Text file is in DIR named folder having a python class and a txt file


class Module:
    def __init__(self):
        file = open('../DIR/temp.txt','r+')
        self.lines = file.readlines()

    def OUT(self):
        print(self.lines)

md = Module()
print(md.OUT())

from DIR.module1 import Module
import DIR
import sys 

md = Module()
print(md.OUT())

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • 1
    Try an absolute path. If that works, you are probably not where you think you are when referencing the relative path. – Patrick Artner Jun 17 '20 at 11:59
  • 1
    Also - have a look at the `with open(...) as file: ...` contextmanager to make reading files saver: https://stackoverflow.com/questions/43757161/why-can-you-use-open-as-context-manager – Patrick Artner Jun 17 '20 at 12:02
  • absolute path wont work as the Code will be tested on different machines absolute path is not useful – Muhammad Mustaqeem Jun 17 '20 at 14:48
  • you should close the file after opening otherwise it will be "locked", best way is to use a context manager like @PatrickArtner suggested – bherbruck Jun 17 '20 at 15:04
  • using an absolute file is to _proof_ you are looking at the wrong directory using relative pathing. if you really need relative pathing, you need to figure out where you are, whats the base dir and where to path torelative to that. See the dupes for how to do that. – Patrick Artner Jun 17 '20 at 15:50

0 Answers0