imp
imp

Reputation: 2087

How to write data in a tabular form in a file

I am using python 2.7 I want to write data to a file in a tabular form in a file. Table contains three columns. And this file will be accessed by different applications. So, this file will remain in the system.

I have to both read and write data. So data should be easily accessible just like sql database.

Upvotes: 1

Views: 3600

Answers (3)

BoshWash
BoshWash

Reputation: 5440

Using SQLite

The sqlite3 module stores sql tables in a single file, without requiring a webserver for access like mySQL.

Writing

c = conn.cursor()

# Create table
c.execute('''CREATE TABLE stocks
             (date text, trans text, symbol text, qty real, price real)''')

# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

# Save (commit) the changes
conn.commit()

To change and remove data you can use the regular SQL statements like UPDATE, SET, DELETE

Reading

t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print c.fetchone()

Closing

# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()

Using CSV

The csv module lets you read and write lists and tables. It's a standard format supported by pretty much every spreadsheet application and programming language.

Writing

import csv

with open('eggs.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

results in:

Spam Spam Spam Spam Spam |Baked Beans|

Spam |Lovely Spam| |Wonderful Spam|

Loading

import csv

with open('eggs.csv', 'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
    print ', '.join(row)

prints:

Spam, Spam, Spam, Spam, Spam, Baked Beans

Spam, Lovely Spam, Wonderful Spam

Upvotes: 4

Pavan Gupta
Pavan Gupta

Reputation: 19223

The csv module implements classes to read and write tabular data in CSV format. It allows programmers to say, “write this data in the format preferred by Excel,” or “read data from this file which was generated by Excel,” without knowing the precise details of the CSV format used by Excel. Programmers can also describe the CSV formats understood by other applications or define their own special-purpose CSV formats.

The csv module’s reader and writer objects read and write sequences. Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes.

Upvotes: 1

Javier
Javier

Reputation: 1087

To write

myList = [['1', '2', '3'], ['4', '5', '6']]
with open('/home/XXXX/whatever.txt', 'w') as file:
    for row in myList:
        file.write(';'.join(row))
        file.write('\n')

To read

myList2 = list()
with open('/home/XXXX/whatever.txt', 'r') as file:
    for row in file.read().splitlines():
        myList2.append(row.split(';'))

Upvotes: 0

Related Questions