Can I use f = open('text', 'w') with processing?

edited April 2018 in Python Mode

I was looking at the writing to a text file using python/processing and noticed that there is something called: "createWriter". Is this the only way? I am used to using: open("text", "w") After several attempts at using "open", I couldn't get it to create the text file BUT, for some reason: open("text", "r") seems to work.

Here is my code : f = open('text.txt', 'w') f.write("hello") f.close() noLoop()

If I have to use CreateWriter, I will, but I was wondering why the "r" works, but the "w" does not?

Answers

  • edited April 2018

    It is highly recommended to use Processing's API functions when dealing w/ files.

    B/c they take into consideration the internal variable sketchPath, which is a String representing the folder our sketch is running from.

    For ".txt" files, Processing's got loadStrings() & saveStrings():

    1. http://Py.Processing.org/reference/loadStrings.html
    2. http://Py.Processing.org/reference/saveStrings.html

    They also have the added bonus of using the encoding UTF-8 btW. \m/

  • edited April 2018

    P.S.: When using Processing's save functions, such as saveStrings(), it is highly recommended to call the undocumented dataPath() passing the String filename: L-)

    saveStrings( this.dataPath('text.txt'), stringArray )

    This way, the file is saved inside sketch's subfolder "data/" instead of its sketchPath's root. :-bd

  • Ok, I tried that and it works thanks. I couldn't get saving txt files until you showed me that. Is there anything undocuments for csv files too?

  • edited April 2018

    Although absent in Python Mode's API reference: http://Py.Processing.org/reference/

    B/c it uses the same Processing library as the main Java Mode, both loadTable() & saveTable() are available from within Python Mode:

    1. https://Processing.org/reference/loadTable_.html
    2. https://Processing.org/reference/saveTable_.html

    So we can handle both ".csv" & ".tsv" files under Python Mode too. :>

  • I am trying this, but nothing gets printed to the console or otherwise. I did try to iterate through table.rows, but got an error saying there was no attribute for rows.

    list1=[]
    def setup():
        table = loadTable("spreadsheet_email.csv")
        print (table)
    
    def draw():
        pass
    

    I am not verse on Java, so I am trying to parse through the links you gave me and figure it out, without much success...Thanks again for the help!

  • edited April 2018

    These are the documented methods for class Table:
    https://Processing.org/reference/Table.html

    B/c the devs haven't @Override the Object::toString() method in class Table: :-B
    https://Docs.Oracle.com/javase/10/docs/api/java/lang/Object.html#toString()

    When we print it, some hexadecimal gibberish is displayed. 8-X

    In order to see its content, we do need to traverse the Table object.
    For that, we can invoke the Table::rows() method: *-:)
    https://Processing.org/reference/Table_rows_.html

    Then use it in a for...in loop: http://Py.Processing.org/reference/for.html
    Something like this: for tr in table.rows(): B-)

    Notice though that the iterator tr is of datatype TableRow now, and got instead these methods:
    https://Processing.org/reference/TableRow.html

  • Ok, I am trying to figure out what you are saying here: 1) The "Tables method" in java has a method of creating tables with columns and rows. 2) I do not get any gibberish when I run the above code in my previous post. 3) The table rows() method gives me this error "nonetype" object has no attribute "rows". 4) I am using the: for i in table.rows() when I get this error. 5) Are you saying that I have to create the spreadsheet using the table function, rather than being able to pull the info from a csv file?

  • edited April 2018
    1. I haven't said anything about any method which creates a Table.
      For that specific case, you'd need to import the Table class.
    2. I've meant when attempt to use print over the variable holding the Table object.
    3. Much probable loadTable() had failed or something else.
    4. If variable table is still None, nothing's gonna work!
    5. Nope! You've asked about loading and saving ".csv" files.
  • Ok, thanks for the clarification, but when I go to import Table, it gives me an error saying there is "no module named Table". Tried the two below with capitalization and lower case:

    import Table
    import loadTable
    
  • edited April 2018

    @netrate -- okay, you seem to be confused about a couple things that are making it harder for you to find solutions.

    1. You don't need to use "import" to access the built-in Processing API. You don't need to import PImage, PVector, Table etc. etc. -- those are built-in. Just use them. Edit: loadTable does not require import, directly creating a Table does, see below

    2. There is already documentation for this -- both the reference, and examples!

    Open up a Python mode sketch, then go to File > Examples. In the Python Examples window, navigate to Topics > Advanced Data > LoadSaveTable. Run the sketch LoadSaveTable.pyde and click to interact. Look at the code. Look at the data/data.csv file in the sketch folder. Notice that every time you click, it saves the updated file to disk.

    Ask more questions here if you still need more help with loading and saving CSV files after looking over this working example!

  • ty, I will look over this example. I appreciate the patience!

  • Not a problem -- here to help. Let us know how it goes!

  • edited April 2018

    You don't need to import PImage, PVector, Table etc. etc. -- those are built-in.

    Even though those 3 classes are builtins, Table isn't visible under Python Mode like the other 2 classes. @-)

    So, in order to instantiate the class Table under Python Mode, we do need to import it 1st:
    from processing.data import Table

    Fortunately, at least loadTable() & saveTable(), which are methods from class PApplet, are already globally visible. >-)

  • in order to instantiate the class Table under Python Mode, we do need to import it 1st

    Good point! Although most demo sketches don't import it -- because if you are instantiating your Table from the built-in loadTable then no import is needed:

    https://github.com/jdf/processing.py/blob/master/mode/examples/Topics/AdvancedData/LoadSaveTable/LoadSaveTable.pyde

  • Ok I think I am getting the read portion of it. I used the example you suggested and set up some columns and read the values in the rows that were associated with the fields.

    name age john 34 bill 66

    I am having some challenges with saving though. Right now I have added a new column called "car" and I am trying to add a integer of the year so it will look like: name age car john 34 2015 bill 66 2018

    I was hoping to put the years in a list and draw from that, but I am getting an error when I do. It says list indices must be integers.

    car_year=[2015, 2018]
    table.addColumn("car");
        for row in table.rows():
            row.setInt("year", car_year[row])
    

    If I set the row.setInt to a single number like this:

    car_year=[2015, 2018]
    table.addColumn("car");
        for row in table.rows():
            row.setInt("year", 2018)
    

    It works but puts 2018 for both John and Bill's rows. I wanted just to read for a list and put them in the proper place using that list indexes. I am hoping it is something simple.

  • edited April 2018
    for row in table.rows():
        row.setInt("year", car_year[row])
    

    row isn't an index integer -- it is a TableRow object, which is why you can call its row.setInt() method. I don't think you can access a list item car_year[TableRow] -- that doesn't make sense.

    It seems like perhaps you want to loop with an index? Example tutorial on approaches:

    Another way of approaching this kind of problem is list comprehension. Example tutorial:

  • So how would I go about writing new data in the CAR field so that is works with each new row adding a different car year for each person?

  • edited April 2018

    "original.csv":

    name,age
    john,34
    bill,66
    

    "Add_New_Column_to_Table.pyde":

    """
     Add New Column to Table (v1.1.3)
     GoToLoop (2018-Apr-17)
    
     Forum.Processing.org/two/discussion/27767/
     can-i-use-f-open-text-w-with-processing#Item_18
    """
    
    from processing.data import Table
    
    def setup():
        table = loadTable('original.csv', 'header')
        table.columnTypes = [Table.STRING, Table.INT]
        printTable(table)
        print
    
        addTableIntCol(table, 'car', 2015, 2018)
        printTable(table)
    
        saveTable(table, this.dataPath('modified.csv'))
        exit()
    
    
    def printTable(t, IDX='[%d] - ', COL='%s: %s\t'):
        for i, tr in enumerate(t.rows()):
            PApplet.print(IDX % i)
    
            for col in t.columnTitles:
                PApplet.print(COL % (col, tr.getString(col)))
    
            print
    
    
    def addTableIntCol(t, col, *items):
        t.addColumn(col, Table.INT)
        setTableIntCol(t, col, *items)
    
    
    def setTableIntCol(t, col, *items):
        it = iter(items)
    
        for tr in t.rows():
            i = next(it, it)
            if i is it: return
            tr.setInt(col, i)
    
Sign In or Register to comment.