0

I have a python script 'main.py' which calls another python script called 'getconf.py' that reads from a file 'configuration.txt'. This is what it looks like:

if __name__ == "__main__":
        execfile("forprolog.py") # this creates configuration.txt
        execfile("getconf.py")

When getconf.py is called via main.py it sees configuration.txt as an empty file and fails to read the string from it.

This is how I read from a file:

f1 = open("configuration.txt")
conf = f1.read() #this string appears to be empty

print f1 returns <open file 'D:\\DIPLOMA\\PLANNER\\Exe\\configuration.txt', mode 'r' at 0x01A080D0>

print f1.read() returns an empty string I suspect the reason of the failure is that the file is being written immediately before calling getconf.py. If I run main.py when configuration.txt is already there it works. Adding a time delay between the actions doesn't solve the problem. Would appreciate any help!

  • 1
    Where is your file stored relative to your `getconf.py`? Is it in the same directory? If not, use the [os](https://docs.python.org/3.4/library/os.path.html) module to build the path. – mihai Apr 17 '15 at 04:48
  • Try providing absolute path. – sumit-sampang-rai Apr 17 '15 at 04:59
  • All three files are in the same directory. Absolute path doesn't seem to help. – annie_apnasf Apr 17 '15 at 05:26
  • I don't believe that it "sees configulration.txt as an empty file", it's rather that you don't notice that it fails to open the file. So go and fix that code first! If all that doesn't help, come back here and provide a minimal but complete example, your code as it stands isn't complete. Also, why don't you just import getconf.py as a module? I'd also consider upgrading to Python3 on the way. – Ulrich Eckhardt Apr 17 '15 at 05:28
  • What does `print f1` and `print f1.read()` return? – vishen Apr 17 '15 at 05:28
  • Have you closed the file after writing to it? Are you sure it's there and actually has content? Try to isolate the problem, try to read another file. – moooeeeep Apr 17 '15 at 06:23

2 Answers2

0

I saw other questions related to this:

Python read() function returns empty string

Try to add this line before reading:

file.seek(0)

https://stackoverflow.com/a/16374481/4733992

If this doesn't solve the problem, you can still get the lines one by one and add them to a single string:

file = open("configuration.txt", 'r')
file_data = ""
for line in file:
    file_data += line
file.close()
Community
  • 1
  • 1
Morb
  • 534
  • 3
  • 14
0

I found my problem, it was due to the fact I didn't close the file that I was writing in. Thanks to all who tried to help.