Read / Write to text file within the Pythonista library
Is it possible to have a text file (eg previousactionlog.txt) held within the Pythnoista library and then read/write to that from your Python scripts? I am looking at a basic way of building a table within my code so that I can store previous details each time some one runs the module. Not sure if I'm being a little stupid here as I'm still a little new to this language. Thanks
You seem to be able to use the standard Python read/write:
It seems that this file can then be accessed by any script within your library.
By the way, is pasted code recognized automatically on the forum? I can't figure out how to preserve indents :(
Edit: Thanks pudquick!
<PRE>with open('hello.txt', 'w+') as f:
y = f.read()
With this format, the file will automatically close after the indent block. If you want to avoid this, use the following format:
<PRE>x = open('hello.txt', 'w+')
z = x.read()
I used w+ because I wanted to read and write from the same file without closing and reopening it. In general, use 'a' to append (as opposed to writing over), 'r' to read, and 'w' to write.
Before the block of code, type: <PRE>
After it, type: </PRE>
It'll come out like:
indent = True
Absolutely! If you need to store objects rather than plain text, have a look at the <a href="http://omz-software.com/pythonista/docs/library/pickle.html">pickle</a> module; if you're familiar with databases, you might find <a href="http://omz-software.com/pythonista/docs/library/sqlite3.html">sqlite3</a> helpful too. The <a href="http://omz-software.com/pythonista/docs/library/json.html">json</a> and <a href="http://omz-software.com/pythonista/docs/library/csv.html">csv</a> modules are also good options for storing small amounts of structured data.
To get started though, writing plain text files, as shown by Steven, is probably the easiest.
To expand on the question, can you browse through the text files? That way you can make changes, view the various files, etc. Can this be done through Pythonista, or is another app needed?