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!

6
  • 1
    Where is your file stored relative to your getconf.py? Is it in the same directory? If not, use the os module to build the path. Commented Apr 17, 2015 at 4:48
  • Try providing absolute path. Commented Apr 17, 2015 at 4:59
  • All three files are in the same directory. Absolute path doesn't seem to help. Commented Apr 17, 2015 at 5: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. Commented Apr 17, 2015 at 5:28
  • What does print f1 and print f1.read() return? Commented Apr 17, 2015 at 5:28

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.