Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
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:
f.write('Hello world')
f.seek(0)
y = f.read()
print y</PRE>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+')
x.write('Hello world')
x.seek(0)
z = x.read()
print z
x.close()</PRE>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:
<PRE>def func():
indent = True
</PRE> -
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?