Python file read, csv file read and write simple example


Here you can find a code piece for reading and writing files using Powerful Python lang.

#Created on Jul 25, 2013

#@author: tuna

file = open('C:\\Users\\tunato\\Desktop\\pythontest.csv', 'r')

#printing file name
print (file.name)

#reading files in an array
#lines = file.readlines()
#print (lines)

#displaying file content line by line
for line in file:
    print (line.rstrip())
file.close()

print ('\n')

#writing to a file
try:
    fh = open('C:\\Users\\tunato\\Desktop\\pythontext.txt', 'w') #opening in write mode
    fh.write('Writing log content inside')
except IOError:
    print ('Error: I/O Error')
else:
    print ('Content is written')

print ('\n')

import csv
#reading file using csv module
with open('C:\\Users\\tunato\\Desktop\\pythontest.csv', 'r') as file:
    reader = csv.reader(file)
    for line in reader:
        print (line)

Output;

C:\Users\tunato\Desktop\pythontest.csv
Customer_ID,Customer_Name,Customer_Surname,Email
1,Tuna,Tore,adm@test.com
2,Henry,Red,adm@test.com
3,Micheal,Green,adm@test.com
4,Liz,Mane,adm@test.com
5,John,Blue,adm@test.com
6,Tom,James,adm@test.com
7,Jim,Bean,adm@test.com
8,Mark,Way,adm@test.com

Content is written

[‘Customer_ID’, ‘Customer_Name’, ‘Customer_Surname’, ‘Email’]
[‘1’, ‘Tuna’, ‘Tore’, ‘adm@test.com’]
[‘2’, ‘Henry’, ‘Red’, ‘adm@test.com’]
[‘3’, ‘Micheal’, ‘Green’, ‘adm@test.com’]
[‘4’, ‘Liz’, ‘Mane’, ‘adm@test.com’]
[‘5’, ‘John’, ‘Blue’, ‘adm@test.com’]
[‘6’, ‘Tom’, ‘James’, ‘adm@test.com’]
[‘7’, ‘Jim’, ‘Bean’, ‘adm@test.com’]
[‘8’, ‘Mark’, ‘Way’, ‘adm@test.com’]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s