Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

April 19, 2017

Python script for file handling - Read & Write

# Basic File Handling in Python - Read & Write
# coding: utf-8 # for Non-ASCII character support

# Writing to a file
f = open("<file path>/file_read_write.txt", "w");
f.write("Name                    Age                  \n")
f.write("-----------------------------------------\n")

mystring = "%s                   (%d) \n" % ("Ram", 32)
f.write(mystring)

f.close() 

# Reading from a file
f = open("<file path>/file_read_write.txt", "r") 
print f.read() 

f.close()

Note:
you may also try the following commands for selective read(s)
    print f.read(4)
    print f.readline()
    print f.readline(3)

April 6, 2017

How to validate an email address using Python Script?

Code snippet to validate the email id taken as an input via command line

# Python script to validate input email address
# for system input
import sys
print(sys.argv)

# for regular expression
import re
print "\n" 

email_id = raw_input("Please enter your email id: ")
if re.match("[^@]+@[^@]+\.[^@]+", email_id):
print "Hurray! you have entered a valid email id: ", email_id
else:
print "Better luck next time with a valid email id"

March 15, 2017

How to upload files to S3 using Python Boto3?

The below script gives you a quick example of uploading a specific file to the S3 bucket, provided the IAM user calling the API has the s3:GetObject permissions on the S3 bucket.

# Boto3 script to upload a file to S3
import boto3
session = boto3.Session(profile_name='<profilename>') #ensure to use appropriate  profile
s3_client = session.client('s3')

print "Upload the your test file to S3"
s3_client.upload_file('<file path>/<file name with extension>', '<s3 bucket name>', '<prefixfolder/filename with extension>)

print "Success! Upload complete"
print "Getting list"
files=s3_client.list_objects(Bucket='<s3 bucket name>', Prefix='<prefixfolder/filename with extension>')['Contents']

for key in files:

   print key