Home/Support/Support Forum/the use of "open" in digi
Welcome to Digi Forum, where you can ask questions and receive answers from other members of the community.

the use of "open" in digi

0 votes
where I type
" logfile = open(a.txt', 'w') " and run in my pc ,it is allright
but,when it run in digi connectPort X4,
will " IOError: [Errno 19] No such device: 'a.txt' "
I do not why? Thanks,help me
asked May 26, 2012 in Python by songsong New to the Community (1 point)

Please log in or register to answer this question.

3 Answers

0 votes
You may have to specify the directory. For example this should work:

open('WEB/a.txt', 'w')
answered May 28, 2012 by kurte New to the Community (29 points)
0 votes
Kurt is correct - some products (like the X2/X4) have no ability to 'change' directories, so 'a.txt' would need to exist in the root of a read-only file-system you don't have access to.

On the X2/X4 (& other connect products)
- 'WEB/a.txt' would exist in the area you access with the web UI under the Administration 'file management'.
- 'WEB/python/a.txt' would exist in the area you access with the web UI under the Applications 'Python'.
answered May 29, 2012 by lynnl Veteran of the Digi Community (1,047 points)
0 votes
Also, it's always a good idea to wrap file/io type operations in a try/catch block. This way, you can do things such as try to open a file to read, and if it's not there, catch the exception and create a new file. The other option is to use the 'if file exists' functionality, that way you can take care of instances where if used for soemthing such as a configuration file for a script and the file was accidentally erased, you can have a clause which will create a new file with some default settings. For instance, something like the following:
if (os.path.exists(self.filename)):
print "file exists"
self._output = open(self.filename, "a")
self._output.close()
else:
print "creating new"
self._output = open(self.filename, "w")
str2write = "Default settings in here."
self._output.write(str2write)
self._output.close()

This was taken from a file logger class I created, so you may not be able to use it line for line, but it should give you an idea as to how to react and handle cases where the file is not there and handling gracefully, instead of causing an unhandled exception.
answered Sep 28, 2012 by nathanf Community Contributor (80 points)
...