Today we discuss about comparing numbers/strings in Perl.
Compare Numbers:
Syntax :
$a == $b (Equal check for numbers)
$a != $b (Not Equal check for numbers)
compare_numbers.pl
#!/usr/bin/perl
use strict;
use warnings;
my $num1 = 100;
my $num2 = 200;
if ($num1 == $num2) {
print "Equal\n";
} else {
print "Not Equal\n";
}
O/P:
Not Equal
Compare Strings:
Syntax :
$a eq $b (Equal check for strings )
$a ne $b (Not Equal check for strings)
compare_strings.pl
#!/usr/bin/perl
use strict;
use warnings;
my $string1 = 'one';
my $string2 = 'two';
if ($string1 eq $string2) {
print "Equal\n";
} else {
print "Not Equal\n";
}
O/P:
Not Equal
PySpark, BigData, SQL, Hive, AWS, Python, Unix/Linux, Shortcuts, Examples, Scripts, Perl
Mar 24, 2013
Compare Numbers/Strings in Perl
Mar 23, 2013
Create Log File in Perl
Today we discuss about how to create a log file in Perl, Logging is always part and parcel in developing code.
Here in the below mentioned example :
1) We are trying to read the lines from the file in the path 'C:\Perl\data.txt'
2) While reading the lines, in case of any errors, we are capturing (means we are writing to log file) to log file 'C:\Perl\log.txt'
3) You can either use write/append mode to log file based on your requirement.
4) Write (">") mode : You write the content to a new log file
5) Append (">>") mode : if Log File already exists, you append the content to the existing file
log_test.pl
#!/usr/bin/perl
use strict;
use warnings;
my $log_file_path = 'C:\Perl\log.txt';
my $read_file_path = 'C:\Perl\data.txt';
#use the ">" symbol to write to new file (Write mode)
#use the ">>" to append to the file (Append mode)
open (LOG_FILE, ">$log_file_path");
open (READ_FILE, "$read_file_path");
#"READ_FILE" is File Handle
unless (-e $read_file_path) {
print LOG_FILE "\n Read File Doesn't Exist!!! : " . $read_file_path;
exit;
}
#use the ">" symbol to write to new file (Write mode)
#use the ">>" to append to the file (Append mode)
while my $each_line (<READ_FILE>) {
print "\n Each Line: :" . $each_line;
}
print LOG_FILE "\nTesting Writing into Perl file";
print LOG_FILE "\nWriting more content 111";
print LOG_FILE "\nWriting more content 222";
close (READ_FILE);
close (LOG_FILE);
O/P:
log.txt (In case file data.txt is present in the path)
Testing Writing into Perl file
Writing more content 111
Writing more content 222
log.txt (In case file data.txt is not present in the path)
Read File Doesn't Exist!!! : log.txt
Read File Doesn't Exist!!! : log.txt
Chop Vs Chomp
Now, we discuss about Chop & Chomp functionality in Perl
Chop:
It removes the last character of the string completely (even if the last character is new line or a character)
Chomp:
It only removes the last character if it is a newline.
Chomp is more useful when we are reading the files to trim the new line characters
Chop: It removes the last character of the string completely
E.g., chop_test.pl
#!/usr/bin/perl
use strict;
use warnings;
$name = "Mother Teresa";
print "Name before chop: " . $name;
chop($name);
print "Name after chop: " . $name;
O/P:
Name before chop : Mother Teresa
Name after chop : Mother Teres
Chomp: It only removes the last character if it is a newline.
E.g., chomp_test.pl
#!/usr/bin/perl
use strict;
use warnings;
$name = "Mother Teresa\n";
print "Name before chomp: " . $name;
chomp($name);
print "Name after chomp: " . $name;
O/P:
Name after chomp: Mother Teresa
Name after chomp: Mother Teresa
Labels:
chomp,
chop,
interview questions,
perl,
perl_basics,
perl_chomp,
perl_chop
Write to File in Perl
Now, we discuss about writing content to a file
The following code snippet explains
1) Write (">") mode : You write the content to a new file
2) Append (">>") mode : File already exists, you append the content to the existing file
3) You can either define Write or Append mode based on your requirement
4) Define a file read handle (FILE_WRITE), it's can be any user defined name
5) Write the contents to file
file_write.pl
#!/usr/bin/perl
use strict;
use warnings;
my $filename = 'C:\Perl\data_write.txt';
#use the ">" symbol to write to new file (Write mode)
#use the ">>" to append to the file (Append mode)
open (FILE_WRITE, ">$filename");
#"FILE_WRITE" is File Handle
print FILE_WRITE "\nTesting Writing into Perl file";
print FILE_WRITE "\nWriting more content 111";
print FILE_WRITE "\nWriting more content 222";
close (FILE_WRITE);
#use the ">" symbol to write to new file
#use the ">>" to append to the file
Output:
data_write.txt
Testing Writing into Perl file
Writing more content 111
Writing more content 222
Labels:
file,
files,
perl_basics,
perl_file,
write_file
Reading File in Perl
Let's discuss about reading a file in Perl with an example.
The following code snippet
1) Checks whether the file (data_read.txt) we are going to read is present or not
2) Define a file read handle (FILE_READ), it's can be any user defined name
3) Loop through the file handle and read line line from the file
2) Chomp each & every line (to remove the new-line characters (e.g., \n)
4) Print the contents of the file line by line
E.g.,
data_read.txt
Mother Teresa
Nelson Mandela
Abraham Lincoln
file_read.pl
#!/usr/bin/perl
use strict;
use warnings;
my $filename = 'C:\Perl\data_read.txt';
#Check if file is present in the path or not
unless (-e $filename) {
print "\n File Doesn't Exist!" . $filename;
exit;
}
#"FILE_READ" is File Handle
open (FILE_READ, $filename);
while (my $each_line = <FILE_READ>) {
#"chomp" removes the new lines characters like "\n" at the end of each line
chomp $each_line;
print $each_line . "\n";
}
close (FILE_READ);
Output:
Mother Teresa
Nelson Mandela
Abraham Lincoln
For Vs Foreach in Perl
Today we discuss about the difference between For & Foreach with simple examples:
FOR Syntax:
Syntax :for (initialization; test; re-initialization) BLOCK
#!/usr/bin/perl
use strict;
use warnings;
print "\nStart For Loop";
for ($count = 1; $count <= 5; $count++) {
print "\nEach Element : " . $count;
}
print "\nEnd For Loop";
O/P:
Start For Loop
Each Element : 1
Each Element : 2
Each Element : 3
Each Element : 4
Each Element : 5
End For Loop
Foreach
The foreach keyword is actually a synonym for the "for" keyword, so we can use "foreach" (more readability or brevity)
#!/usr/bin/perl
use strict;
use warnings;
@array = ("Mother Teresa", "Abraham Lincoln", "Nelson Mandela");
foreach my $each (@array) {
print "\nEach Element : " . $each;
}
O/P:
Each Element : Mother Teresa
Each Element : Abraham Lincoln
Each Element : Nelson Mandela
For Loop in Perl
FOR Loop Syntax in Perl:
Syntax:
for (initialization; test; re-initialization) BLOCK
#!/usr/bin/perl
use strict;
use warnings;
print "\nStart For Loop";
for ($count = 1; $count <= 5; $count++) {
print "\nEach Element : " . $count;
}
print "\nEnd For Loop";
O/P:
Start For LoopEach Element : 1
Each Element : 2
Each Element : 3
Each Element : 4
Each Element : 5
End For Loop
Mar 19, 2013
Python - Filter Vs Map Vs Reduce Vs List Comprehension
Today we discuss about the following topics :
1) Filter
2) Map
3) List Comprehension
Lets discuss with few examples:
Filter :
filter(function, sequence) returns a sequence consisting of those items from the sequence for which function(item) is true
Map :
map(function, sequence) calls function(item) for each of the sequence's items and returns a list of the return values
List Comprehension :
List comprehension in Python provides a clear and concise syntax for creating lists from other lists
filter_test.py
Output:
filter_lambda_test.py
Output:
map_test.py
Output:
smallest_no_using_reduce_test.py
#how to use if else in lambda
from functools import reduce
1) Filter
2) Map
3) List Comprehension
Lets discuss with few examples:
Filter :
filter(function, sequence) returns a sequence consisting of those items from the sequence for which function(item) is true
Map :
map(function, sequence) calls function(item) for each of the sequence's items and returns a list of the return values
List Comprehension :
List comprehension in Python provides a clear and concise syntax for creating lists from other lists
filter_test.py
#filter(function, sequence) returns a sequence consisting of those items from the sequence for which function(item) is true
def isPythonFile(list_1):
if list_1.find(".py") == -1:
return False
else:
return True
list_1 = ["1.py","2.pl", "3.zip", "4.py","5.php" ]
py_files = filter(isPythonFile, list_1) #Function is called for each element of list
for item in py_files:
print("Each item in Filetr :" , item)
Output:
Each item in Filetr : 1.py Each item in Filetr : 4.py
filter_lambda_test.py
foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
print("Before Lambda :", list(foo))
print("After Lambda :", list(filter(lambda x: x % 3 == 0, foo)))
Output:
Before Lambda : [2, 18, 9, 22, 17, 24, 8, 12, 27] After Lambda : [18, 9, 24, 12, 27]
map_test.py
print("Before Map :", list(foo))
print("After Map :", list(map(lambda x: x * 2 + 10, foo)))
Output:
Before Map : [2, 18, 9, 22, 17, 24, 8, 12, 27] After Map : [14, 46, 28, 54, 44, 58, 26, 34, 64]
smallest_no_using_reduce_test.py
#how to use if else in lambda
from functools import reduce
ll = [10, 12, 45, 2, 100]
out = reduce(lambda x, y: x if x < y else y, ll)
print(out)
Output:
2
largest_no_using_reduce_test.py
#how to use if else in lambda
from functools import reduce
list_comprehension_test1.py
Output:
list_comprehension_test2.py
Output:
list_comprehension_test3.py (if-else inside list comprehension)
Output:
Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl
You might also wish to read other topics like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton
out = reduce(lambda x, y: x if x < y else y, ll)
print(out)
Output:
2
largest_no_using_reduce_test.py
#how to use if else in lambda
from functools import reduce
ll = [10, 12, 45, 2, 100]
out = reduce(lambda x, y: x if x > y else y, ll)
print(out)
Output:
100
out = reduce(lambda x, y: x if x > y else y, ll)
print(out)
Output:
100
list_comprehension_test1.py
input_arr = [2, 3, 4]
output_arr = [2*i for i in input_arr if i > 2]
print("List Comprehension Test 1 :", output_arr)
Output:
List Comprehension Test 1 : [6, 8]
list_comprehension_test2.py
input_arr = ['Mother Teresa', 'Abraham Lincoln', 'Nelson Mandela']
output_arr = ['Dear...' + i for i in input_arr if len(i) > 5]
print("List Comprehension Test 2 :",output_arr)
Output:
List Comprehension Test 2 : ['Dear...Mother Teresa', 'Dear...Abraham Lincoln', 'Dear...Nelson Mandela']
list_comprehension_test3.py (if-else inside list comprehension)
input_arr = [20, 30, 40, 33, 55]
output_arr = [2*i if i%2 == 0 else i for i in input_arr]
print("List Comprehension Test 3 :", output_arr)
Output:
List Comprehension Test 3 : [40, 60, 80, 33, 55]
Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl
You might also wish to read other topics like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton
Labels:
python_basics,
python_filter,
python_list_comprehension,
python_map,
python_reduce,
python_scripts
Mar 18, 2013
Python User Defined Exceptions
Today we discuss about raising exceptions manually (Python User Defined Exceptions).
1) We already know we have built in exceptions in Python like ValueError, IOError, FileNotFoundError, ZeroDivisionError
2) But sometimes we might have to write custom exceptions on our own to catch few scenarios.
Lets discuss how to implement user defined exception with an example.
In the below example :
nonEmptyValException #User Defined Exception
ValueError, ZeroDivisionError, EOFError #Built-in Exceptions
exceptions_raise_manual.py
import sys
class nonEmptyValException(Exception):
'''A user-defined exception class.'''
def __init__(self, num):
Exception.__init__(self)
self.num = num
try:
a = int(input('Enter some integer for Dividend --> '))
b = int(input('Enter some integer for Divisor --> '))
if not a:
raise nonEmptyValException(a)
if not b:
raise nonEmptyValException(b)
c = a/b;
print ("Final Value is : ", c)
except ValueError:
print('ValueError: Please enter only Integer Value')
except ZeroDivisionError:
print('ZeroDivisionError: The input divisor is %d, was expecting a Non-Zero number' % (b))
except EOFError:
print('\nWhy did you do an EOF on me?')
except nonEmptyValException as error:
print('nonEmptyValException: The input is %d, was expecting a integer number' % (error.num))
Please refer to other Python Exceptions Concepts :
All Python Exceptions Related Topics
Exceptions in Python
Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl
You might also wish to read other topics like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton
Labels:
FileNotFoundError,
IOError,
python_exceptions,
python_scripts,
ValueError,
ZeroDivisionError
Mar 17, 2013
Python Regular Expressions (re.compile Vs re.match)
Today we discuss about the following topics :
1) Pre-compiled Regular Expressions - Uses & Advantages (General Concept)
2) Explain the difference between Python re.compile Vs re.match with an example.
Let's dive into the topic & continue the fun :
1) Pre-compiled Regular Expressions - Uses & Advantages (General Concept)
This is a general topic irrespective of any language (Perl or Python or any)
The extra mile of using a pre-compiled regular expression is :
a) When you have to execute the same regular expression pattern over millions of lines (say reading lines a file), then pre-compiled regular expressions are very handy by drastically reducing the time of execution.
b) Since the regex pattern is pre-compiled in advance, no need to process the regex pattern each and every time while reading the lines from the file (suppose millions of lines in the file)
c) Here, we assume, the regex pattern which you have to use, should be constant, if has to vary every time then pre-compiled regex will not be that useful.
2) Explain the difference between Python re.compile Vs re.match with an example.
Let us explain the explain with a lucid example.
Here we are trying to run a regex pattern in loop of 100000 times with both Python re.compile(pre-complied) & re.match
Please check the time difference between in the output file.
E.g., regex_compile_vs_match.py
You might wish to read Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl
You might also wish to read other topics like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton
1) Pre-compiled Regular Expressions - Uses & Advantages (General Concept)
2) Explain the difference between Python re.compile Vs re.match with an example.
Let's dive into the topic & continue the fun :
1) Pre-compiled Regular Expressions - Uses & Advantages (General Concept)
This is a general topic irrespective of any language (Perl or Python or any)
The extra mile of using a pre-compiled regular expression is :
a) When you have to execute the same regular expression pattern over millions of lines (say reading lines a file), then pre-compiled regular expressions are very handy by drastically reducing the time of execution.
b) Since the regex pattern is pre-compiled in advance, no need to process the regex pattern each and every time while reading the lines from the file (suppose millions of lines in the file)
c) Here, we assume, the regex pattern which you have to use, should be constant, if has to vary every time then pre-compiled regex will not be that useful.
2) Explain the difference between Python re.compile Vs re.match with an example.
Let us explain the explain with a lucid example.
Here we are trying to run a regex pattern in loop of 100000 times with both Python re.compile(pre-complied) & re.match
Please check the time difference between in the output file.
E.g., regex_compile_vs_match.py
import re
import time
input_str = "Mother Teresa"
count_compile = 0
count_match = 0
time_val_1 = time.time()
compiled_regex = re.compile('(\w+)\s+(\w+)')
for i in range(1000000):
if compiled_regex.match(input_str):
count_compile += 1
print ("Count Compile Value : ", count_compile)
print("Time taken by Using Compile : ", time.time() - time_val_1)
time_val_2 = time.time()
for i in range(1000000):
if re.match('(\w+)\s+(\w+)', input_str):
count_match += 1
print ("Count Match Value : ", count_compile)
print("Time taken by Using Match : ", time.time() - time_val_2)
Output:
Count Compile Value : 1000000 Time taken by Using Compile : 1.340999994277954 Count Math Value : 1000000 Time taken by Using Match : 2.994999885559082
You might wish to read Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl
You might also wish to read other topics like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton
Labels:
python_basics,
python_re,
python_re_compile,
python_re_match,
python_re_search,
python_regex,
python_scripts,
regex,
regexp,
regular expressions
Mar 15, 2013
How to remove duplicate lines from a file in Python
Today, we will discuss removing duplicate lines from a file in Python
You may also wish to read Object Oriented Concepts in Python as mentioned :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in perl
Lets discuss in two ways as mentioned below :
1) Removing duplicate lines and print the lines in order (When Order is important)
- Using normal way
2) Removing duplicate lines and print the lines in any order (When Order is NOT important)
- Using SET concept in Python. SET concept in python does not consider Order.
Note:
Both the scripts read duplicated content from file_with_duplicates.txt,
Read the above file and remove duplicate lines and finally
Print to file_without_duplicates.txt
Input: file_with_duplicates.txt
1) remove_duplicate_lines_from_file_with_order.py
- Using Normal Way - it take cares of order of the lines
Output: file_without_duplicates.txt
2) remove_duplicate_lines_from_file_without_order.py
- Using SET concept - it does not consider the order of the lines
Output: file_without_duplicates.txt
Note:
Both the scripts read duplicated content from file_with_duplicates.txt,
Read the above file and remove duplicate lines and finally
Print to file_without_duplicates.txt
Input: file_with_duplicates.txt
Mother Teresa Winston Churchill Abraham Lincoln Mahatma Gandhi Winston Churchill Mother Teresa Abraham Lincoln
1)
infile = open('file_with_duplicates.txt', 'r')outfile = open('file_without_duplicates.txt', 'w')lines_seen = set()for line in infile:if line not in lines_seen:outfile.write(line)lines_seen.add(line)outfile.close()
1) remove_duplicate_lines_from_file_with_order.py
- Using Normal Way - it take cares of order of the lines
#!/usr/bin/python
try:
input_file = open("file_with_duplicates.txt", "r")
output_file = open("file_without_duplicates.txt", "w")
unique = []
for line in input_file:
line = line.strip()
if line not in unique:
unique.append(line)
input_file.close()
for i in range(0, len(unique)-1):
unique[i] += "\n"
output_file.writelines(unique)
output_file.close
except FileNotFoundError:
print('\n File NOT Found Error')
sys.exit
except IOError:
print('\n IO Error')
sys.exit
Output: file_without_duplicates.txt
Mother Teresa Winston Churchill Abraham Lincoln Mahatma Gandhi
2) remove_duplicate_lines_from_file_without_order.py
- Using SET concept - it does not consider the order of the lines
#!/usr/bin/python
try:
input_file = open("file_with_duplicates.txt", "r")
output_file = open("file_without_duplicates.txt","w")
#The main drawback of using sets is, the order of the lines may not be same as in input file
uniquelines = set(input_file.read().split("\n"))
output_file.write("".join([line + "\n" for line in uniquelines]))
input_file.close()
output_file.close()
except FileNotFoundError:
print('\n File NOT Found Error')
sys.exit
except IOError:
print('\n IO Error')
sys.exit
Output: file_without_duplicates.txt
Abraham Lincoln Winston Churchill Mother Teresa Mahatma Gandhi
You may also wish to read Object Oriented Concepts in Python as mentioned :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in perl
Mar 14, 2013
How to remove duplicate lines from a file in perl
Today, we discuss about the following :
1) How to open the directory & read all the files
2) In each file, remove duplicate lines from a file and keep it in same path/file or different path/file
4) How to create time-stamp in Perl
3) How to create a log file and log the changes
Mention the corresponding path where you want to copy
e.g., If you want to remove duplicated line and copy in the same file
my $input_dir = "/nfs/fm/disks/my_files";
my $output_dir = "/nfs/fm/disks/my_files";
my $log_dir = "/nfs/fm/disks/my_files";
e.g., If you want to copy the output of the files in different locations
my $input_dir = "/nfs/fm/disks/input_dir";
my $output_dir = "/nfs/fm/disks/output_dir";
my $log_dir = "/nfs/fm/disks/log_fir";
remove_duplicates.pl
You may also wish to read Object Oriented Concepts in Python as mentioned :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
1) How to open the directory & read all the files
2) In each file, remove duplicate lines from a file and keep it in same path/file or different path/file
4) How to create time-stamp in Perl
3) How to create a log file and log the changes
Mention the corresponding path where you want to copy
e.g., If you want to remove duplicated line and copy in the same file
my $input_dir = "/nfs/fm/disks/my_files";
my $output_dir = "/nfs/fm/disks/my_files";
my $log_dir = "/nfs/fm/disks/my_files";
e.g., If you want to copy the output of the files in different locations
my $input_dir = "/nfs/fm/disks/input_dir";
my $output_dir = "/nfs/fm/disks/output_dir";
my $log_dir = "/nfs/fm/disks/log_fir";
remove_duplicates.pl
#!/usr/bin/perl
use strict;
use warnings;
my $input_dir = "/nfs/fm/disks/my_files";
my $output_dir = "/nfs/fm/disks/my_files";
my $log_dir = "/nfs/fm/disks/my_files";
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst);
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$sec = sprintf("%02d",$sec);
$min = sprintf("%02d",$min);
$hour = sprintf("%02d",$hour);
$mday = sprintf("%02d", $mday);
$mon = sprintf("%02d", $mon+1);
$year = sprintf("%04d", $year+1900);
my $output_tag = $mday .'_'. $mon .'_'. $year .'_'. $hour .'_'. $min;
opendir(IN_DIR, $input_dir) or die $!;
opendir(OUT_DIR, $output_dir) or die $!;
opendir(LOG_DIR, $log_dir) or die $!;
open (LOG_FILE, "> $log_dir/remove_duplicate_lines.log");
print LOG_FILE "------------- START ------------ \n";
my (@invalid_list_files, %file_without_dup );
while (my $file = readdir(IN_DIR)) {
next if $file =~ /^\./;
print LOG_FILE "\n Folder Path : " , "$input_dir/$file";
unless (-f "$input_dir/$file") {
print LOG_FILE "\n Not a File : " . $file;
next;
}
print LOG_FILE "\n File Name : " . $file . "\n";
#Reading the File
open(IN_FILE, "<$file") || die "\n Cant open file for reading: " . $file;
my @lines =
close(IN_FILE);
my @newlines;
foreach my $each_line (@lines) {
if (not defined $file_without_dup{$each_line}) {
push(@newlines, $each_line);
}
$file_without_dup{$each_line} = 1;
}
#Writing into Output Files
open(OUT_FILE, ">$output_dir/$file") || die "-W- Cant open file for writing: " . "$output_dir/$file";
print OUT_FILE @newlines;
close(OUT_FILE);
}
close (LOG_FILE);
closedir(IN_DIR);
closedir(OUT_DIR);
closedir(LOG_DIR);
1;
You may also wish to read Object Oriented Concepts in Python as mentioned :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
Labels:
duplicate,
duplicate_files,
duplicates,
perl_script
Mar 12, 2013
Exceptions in Python
Today, we discuss about the following :
1) Try block in Python
2) finally block
3) Exceptions
-> In the following example, we can catch exceptions occurred in the code.
-> Keep the code in try block, when an exception is there, it is being caught by except
-> Finally block will be called at the last after the end of execution of the block.
-> In this example, there are few well know exceptions like FileNotFoundError, IOError, EOFError, ValueError
read.txt (Input File)
exceptions_test.py
You may also wish to read Object Oriented Concepts in Python as mentioned :
Python Class and Object Example
Inheritance in Python
Packages in Python
1) Try block in Python
2) finally block
3) Exceptions
-> In the following example, we can catch exceptions occurred in the code.
-> Keep the code in try block, when an exception is there, it is being caught by except
-> Finally block will be called at the last after the end of execution of the block.
-> In this example, there are few well know exceptions like FileNotFoundError, IOError, EOFError, ValueError
read.txt (Input File)
Abraham Lincoln Mother Teresa Paul Coelho
exceptions_test.py
import time
import sys
try:
f = open('read.txt', 'r')
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
time.sleep(0.5) #1/2 sec
print(line)
except FileNotFoundError:
print('\n File NOT Found Error')
sys.exit
except IOError:
print('\n IO Error')
sys.exit
except EOFError:
print('\nWhy did you do an EOF on me?')
sys.exit
except ValueError:
print("\nValue Error.")
sys.exit
finally:
f.close()
print('Cleaning up...closed the file')
You may also wish to read Object Oriented Concepts in Python as mentioned :
Python Class and Object Example
Inheritance in Python
Packages in Python
Labels:
FileNotFoundError,
IOError,
python,
python_basics,
python_exceptions,
python_try_catch,
python_try_catch_finally,
ValueError
Mar 11, 2013
Packages in Python
Today, We discuss about the following :
1) how to create and use a Package in Python with a simple example.
2) Use of __init__.py
3) How to import classes/function and how to use them
Lets take a ride.
Create a folder structure as mentioned below (Where the package name is Package_Sample):
Package_Sample/__init__.py
Package_Sample/A.py
Package_Sample/B.py
Package_Sample/test.py
Package_Sample/sub_folder/C.py
Package_Sample/sub_folder/D.py
Use of __init__.py
In this file, we define the path of all the files & functions to be imported required for the project.
Once you define here, all these classes/functions, you can access directly, we discuss about this in a short while
e.g.,
from A import *
from B import *
from sub_folder.C import *
from sub_folder.D import *
How to use classes defined in __init__.py
Once you have defined in __init__.py
You can directly access functions of C & D (which are in the path Package_Sample/sub_folder/)
Main advantage is that you no need to specify the whole path (sub_folder) again and again.
e.g.,
from Package_Sample import A
from Package_Sample import B
from Package_Sample import C
from Package_Sample import D
Package_Sample/__init__.py
''' Once you have defined in __init__.py You can directly access functions of C & D (which are in the path Package_Sample/sub_folder/) Main advantage is that you no need to specify the whole path (sub_folder) again and again. ''' from A import * from B import * from sub_folder.C import * from sub_folder.D import *
Package_Sample/A.py
class A:
def __init__(self, type, height, price, age):
self.type = type
self.height = height
self.price = price
self.age = age
def print_details(self):
print("\nThis A Type is :" + self.type + " type ")
print("This A Height is :" + self.height + " foot ")
print("This A Price is :" , str(self.price) + " dollars ")
print("This A Age is :" , str(self.age) + " years")
Package_Sample/B.py
class B:
def __init__(self, type, height, price, age):
self.type = type
self.height = height
self.price = price
self.age = age
def print_details(self):
print("\nThis B Type is :" + self.type + " type ")
print("This B Height is :" + self.height + " foot ")
print("This B Price is :" , str(self.price) + " dollars ")
print("This B Age is :" , str(self.age) + " years")
Package_Sample/test.py
#Testing __init__.py
from Package_Sample import A
from Package_Sample import B
from Package_Sample import C
from Package_Sample import D
cfcpiano_A = A("AAAA", "100 Cms", 11000, 10) #Constructor or Creating Object for Class A
cfcpiano_A.print_details()
cfcpiano_B = B("BBBB", "200 Cms", 22000, 20) #Constructor or Creating Object for Class B
cfcpiano_B.print_details()
cfcpiano_C = C("CCCC", "300 Cms", 33000, 30) #Constructor or Creating Object for Class C
cfcpiano_C.print_details()
cfcpiano_D = D("DDDD", "400 Cms", 44000, 40) #Constructor or Creating Object for Class D
cfcpiano_D.print_details()
Package_Sample/sub_folder/C.py
class C:
def __init__(self, type, height, price, age):
self.type = type
self.height = height
self.price = price
self.age = age
def print_details(self):
print("\nThis C Type is :" + self.type + " type ")
print("This C Height is :" + self.height + " foot ")
print("This C Price is :" , str(self.price) + " dollars ")
print("This C Age is :" , str(self.age) + " years")
Package_Sample/sub_folder/D.py
class D:
def __init__(self, type, height, price, age):
self.type = type
self.height = height
self.price = price
self.age = age
def print_details(self):
print("\nThis D Type is :" + self.type + " type ")
print("This D Height is :" + self.height + " foot ")
print("This D Price is :" , str(self.price) + " dollars ")
print("This D Age is :" , str(self.age) + " years")
How to Run :
Package_Sample/]# python test.py
You may also wish to read Object Oriented Concepts in Python as mentioned :
Python Class and Object Example
Inheritance in Python
Labels:
__init__.py,
python,
python_oops,
python_package
Python Class and Object Example
Lets discuss the basic Object-Oriented concept of Class & Object in Python with a simple example.
Lets create a Person Class and create objects for the Person class.
Python_Class_Object.py (Copy the below snippet and run the program)
You may also wish to read Object Oriented Concepts in Python as mentioned :
Inheritance in Python
Lets create a Person Class and create objects for the Person class.
Python_Class_Object.py (Copy the below snippet and run the program)
class Person:
'''Represents a person.'''
count = 0
def __init__(self, name):
'''Initializing data.'''
self.name = name
print('\n Initializing %s' % self.name)
# To count the people
Person.count += 1
def displayName(self):
''' Saying Hello'''
print('My name is %s.' % self.name)
def count_people(self):
'''Prints the count.'''
if Person.count == 1:
print('I am the only person here.')
else:
print('We have %d persons here.' % Person.count)
Winston = Person('Winston Churchil')
Winston.displayName()
Winston.count_people()
Abraham = Person('Abraham Lincoln')
Abraham.displayName()
Abraham.count_people()
You may also wish to read Object Oriented Concepts in Python as mentioned :
Inheritance in Python
Labels:
python,
python_basics,
python_class,
python_oops
Inheritance in Python
Lets discuss about Inheritance in Python using an example... Lets take a ride...
Here we consider Vehicle as Parent Class where as Car & Truck are sub-classes which inherit from the Parent class(Vehicle).
Here we consider Vehicle as Parent Class where as Car & Truck are sub-classes which inherit from the Parent class(Vehicle).
class Vehicle:
'''Represents any Vehicle.'''
def __init__(self, name, model):
self.name = name
self.model = model
print('Initialized Vehicle: %s' % self.name)
def details(self):
'''Call my details.'''
print('Name:"%s" model:"%s"' % (self.name, self.model))
class Car(Vehicle):
'''Represents a Car.'''
def __init__(self, name, model, price):
Vehicle.__init__(self, name, model)
self.price = price
print('Initialized Car: %s' % self.name)
def details(self):
Vehicle.details(self)
print('price: "%d"' % self.price)
class Truck(Vehicle):
'''Represents a Truck.'''
def __init__(self, name, model, price):
Vehicle.__init__(self, name, model)
self.price = price
print('Initialized Truck: %s' % self.name)
def details(self):
Vehicle.details(self)
print('price: "%d"' % self.price)
c = Car('Cooper', 100, 30000)
t = Truck('Jeep', 200, 50000)
print() # prints a blank line
vehicles = [c, t]
for member in vehicles:
print() # prints a blank line
member.details() # works for both Cars and Trucks
Labels:
inheritance,
python,
python_inheritance,
python_oops
Feb 13, 2013
Python Interview Questions - Part 1
1) Get Unique Items in an array :
Set : Another data type in Python, where copies are not allowed.
List: Sequence of elements just like array
>>> a = [1, 2, 2, 3]
>>> set(a)
{1, 2, 3} #Flower brackets
>>> list(set(a))
[1, 2, 3]
>>> langs = ['Perl', 'PHP', 'Python', 'Java', 'C', 'Ruby', 'perl', 'Perl', 'PERL']
>>> for each_lang in sorted(set(langs)):
... print each_lang
O/P:
C
Java
PERL
PHP
Perl
Python
Ruby
perl
2) What is a docstring in Python?
Docstring is the documentation string for a function.
It prints the comments given inside the function
It can be accessed by <function_name>.__doc__
>>>def func_test():
""" Test Comments 1
Test Comments 2
Test Comments 3 """
>>> func_test.__doc__
3) How to loop/iterate through dict in Python
>>> Countries = {'India': 'New Delhi', 'USA': 'Washington', 'China' : 'Beijing', 'Japan' : 'Tokyo'}
>>> for country, capital in Countries.iteritems(): #Old Version
... print country, capital
...
>>> for country, capital in Countries.items(): #New Version
... print(country, capital)
...
India New Delhi
China Beijing
USA Washington
Japan Tokyo
4) How to Strip End of Line chars in Python (e.g., \n)
rstrip()
C:\Prabhath\Technical\Python\Python_Scripts\read.txt
Gandhi
Abraham Lincoln
Winston Churchill
>>> file = open("C:\\Prabhath\\Technical\\Python\\Python_Scripts\\read.txt", "r")
>>> text = file.readlines()
>>> file.close()
>>> for line in text:
>>> print (len(line.rstrip()))
rstrip() is an inbuilt function which strips the string from the right end of spaces or tabs (special chars like \n etc.,)
Output:
6
15
17
5) Sorting an Array in Python
>>>arr_sort = [10, 50, 90, 80, 35, 56, 45, 98]
>>>arr_sort.sort() #It will sort and keep the result in arr_sort
>>>arr_sort #When U print this, it shows the result [10, 35, 45, 50, 56, 80, 90, 98]
sorted(x) #prints the result [10, 35, 45, 50, 56, 80, 90, 98]
list.sort vs sorted()
list.sort() #sortls only lists
sorted() function accepts any iterable
e.g.,
>>> sorted("Python in demand NOW".split(), key=str.lower)
['demand', 'in', 'NOW', 'Python']
6) Convert Strings to Integers
>>>num_strs = ['11','121','153','184','150','166','17','138','19']
>>>num_int = [int(i) for in in num_strs] #[11, 121, 153, 184, 150, 166, 17, 138, 19]
(or)
>>>num_strs = ['11','121','153','184','150','166','17','138','19']
>>>list(map(int, num_strs)) #[11, 121, 153, 184, 150, 166, 17, 138, 19]
>>>map(int, num_strs) #<map object at 0x0000000002A7AF28>
7) Program to swap two numbers (Python)
a = 500
b = 900
>>>a,b = b,a
8) How to use join in Python
>>> ss = 'abc def ghi'
>>> ss.split() #splits based on space, equivalent to ss.split("\s")
['abc', 'def', 'ghi']
>>> ''.join(ss.split())
'abcdefghi'
Labels:
python,
python_basics,
python_interview_questions
Jan 2, 2013
Dict keys and values in Python
Dict in Python consists of Key & Value pairs. This is similar to Hash concept in Perl language.
Keys are unique in Dict, Values are not necessarily unique in nature.
relatives = {"Lisa" : "daughter", "Bart" : "son", "Marge" : "mother", "Homer" : "father", "Santa" : "dog"}
#raw_input(), print for Python 2.X Version
#input(), print() for Python 3.X Version
for member in sorted(relatives.keys()):
#print "\n",member
print("\n",member)
for member in sorted(relatives.values()):
#print "\n",member
print("\n",member)
Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python
Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension
Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python
Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl
You might also wish to read other topics like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton
Dict Example in Python
Today, we discuss about the Dict concept in Python.
Dict in Python consists of Key & Value pairs. This is similar to Hash concept in Perl language.
Keys are unique in Dict, Values are not necessarily unique in nature.
Let's discuss with an example, let's dive & have fun :
relatives = {"Lisa" : "daughter", "Bart" : "son", "Marge" : "mother", "Homer" : "father", "Santa" : "dog"}
#raw_input(), print for Python 2.X Version
#input(), print() for Python 3.X Version
#Keys are unique
relatives['Marge'] = "mother";
relatives['marge'] = "mother1";
#'Marge' and 'marge' are different keys
for member in sorted(relatives.keys()):
print("\n",member, "=>", relatives[member])
#print "\n",member
for member in sorted(relatives.values()):
print("\n",member)
#print "\n",member
for key, value in relatives.items():
print("\n", key, "=>", value)
#print "\n", key, "=>", value
Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python
Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension
Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl
You might also wish to read other topics like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton
Dict in Python consists of Key & Value pairs. This is similar to Hash concept in Perl language.
Keys are unique in Dict, Values are not necessarily unique in nature.
Let's discuss with an example, let's dive & have fun :
relatives = {"Lisa" : "daughter", "Bart" : "son", "Marge" : "mother", "Homer" : "father", "Santa" : "dog"}
#raw_input(), print for Python 2.X Version
#input(), print() for Python 3.X Version
#Keys are unique
relatives['Marge'] = "mother";
relatives['marge'] = "mother1";
#'Marge' and 'marge' are different keys
for member in sorted(relatives.keys()):
print("\n",member, "=>", relatives[member])
#print "\n",member
for member in sorted(relatives.values()):
print("\n",member)
#print "\n",member
for key, value in relatives.items():
print("\n", key, "=>", value)
#print "\n", key, "=>", value
Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python
Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension
Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl
You might also wish to read other topics like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton
Append to list in Python
inspiring_ppl = ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs"]
#raw_input(), print for Python 2.X Version
#input(), print() for Python 3.X Version
new_insp_ppl = "prabhath"
inspiring_ppl.append(new_insp_ppl)
o/p:
inspiring_ppl = ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs", "prabhath"]
Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension
Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl
You might also wish to read other topics like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton
Delete the last name from the list in Python
inspiring_ppl = ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs", "Abdul Kalam"]
#raw_input(), print for Python 2.X Version
#input(), print() for Python 3.X Version
del inspiring_ppl[-1] #removes Abdul Kalam
print ("The following inspiring_ppl are :", inspiring_ppl)
#print "The following inspiring_ppl are :", inspiring_ppl
#o/p:
#inspiring_ppl = ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs"]
Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension
Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl
You might also wish to read other topics like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton
Remove an element from List in Python
inspiring_ppl = ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs"]
new_inspiring_ppl = inspiring_ppl[:]
#Note:
#raw_input(), print for Python 2.X Version
#input(), print() for Python 3.X Version
for person in new_inspiring_ppl:
print("Do you want to keep person", person, "?")
#print "Do you want to keep person", person, "?"
answer = input("yes/no ")
#answer = raw_input ("yes/no ")
if answer != "yes":
inspiring_ppl.remove(person)
print(inspiring_ppl)
#print inspiring_ppl
Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension
Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl
You might also wish to read other topics like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton
Python difference between list copy and reference
inspiring_ppl = ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs"]
#The following Shares same memory location
inspiring_ppl_1 = inspiring_ppl
inspiring_ppl.append("Abdul Kalam")
inspiring_ppl_1.append("Abraham Lincoln")
#Therefore inspiring_ppl, inspiring_ppl_1 contains the same contents including "Abdul Kalam" and "Abraham Lincoln"
#Python does not have variables like C
#In Python variables are just tags attached to objects
#The following shares different memory location
inspiring_ppl_2 = inspiring_ppl[:]
inspiring_ppl.append("Swami Vivekananda")
print(inspiring_ppl)
o/p: ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs", "Abdul Kalam", "Abraham Lincoln"]
print(inspiring_ppl_1)
o/p: ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs", "Abdul Kalam", "Abraham Lincoln"]
print(inspiring_ppl_2)
o/p: ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs", "Swami Vivekananda"]
Check an element exists in an array/list in Python
inspiring_ppl = ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs"]
#raw_input(), print for Python 2.X Version
#input(), print() for Python 3.X Version
another_person = input("Enter person Name : ")
if another_person in inspiring_ppl:
inspiring_ppl.remove(another_person)
else:
inspiring_ppl.append(another_person)
print(inspiring_ppl)
How to copy a list into another
inspiring_ppl = ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs"]
more_inspiring_ppl = inspiring_ppl[:]
more_inspiring_ppl.reverse()
print inspiring_ppl #2.X Version
#print (inspiring_ppl) #3.X Version
print more_inspiring_ppl #2.X Version
#print (more_inspiring_ppl) #3.X Version
For Loop in Python
inspiring_ppl = ["Mahatma Gandhi", "Mother Teresa", "Paul Coelho", "Bill Gates", "Steve Jobs"]
for person in inspiring_ppl:
print "Hello", person + ", how are you?" #3.X Version
#print("Hello", person + ", how are you?") #2.X Version
Reading a File with line numbers
file = open("read.txt","r")
text = file.readlines()
file.close()
counter = 1
for line in text:
print counter, line,
counter = counter +1
File Operations in Python
file = open("read.txt","r")
text = file.readlines() #Read lines from read.txt
file.close()
file2 = open ("write.txt", "w")
#Write all lines from read.txt into write.txt
#It overrides if any content already present in write.txt
file2.writelines(text)
file2.close
file2 = open ("append.txt", "a")
#It appends content from read.txt into append.txt
file2.writelines(text)
file2.close
Print File Content in Python
file = open("read.txt","r")
text = file.readlines() #Reads the file content
file.close()
for line in text:
print line #Python 2.X Versions
#print(line) #Python 3.X Versions
Print File in Reverse Order in Python
file = open("read.txt","r")
text = file.readlines() #Reads the file content
file.close()
text.reverse() #It reverses the content
for line in text:
print line #Python 2.X Versions
#print(line) #Python 3.X Versions
Labels:
python,
python_basics,
python_file,
python_scripts
Subscribe to:
Posts (Atom)