简体   繁体   中英

Python script fails to read a file

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!

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()

我发现了我的问题,这是由于我没有关闭正在写入的文件。感谢所有尝试提供帮助的人。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM