2017년 8월 8일 화요일

Python Sample


  • Write, Append, Read of file

f = open("C:/Python/new_file.txt", 'w')
f.write("1111")
f.close()

f = open("C:/Python/new_file.txt", 'a')
f.write("2222")
f.close()

f = open("C:/Python/new_file.txt", 'r')
lines = f.readlines()
for line in lines:
    print(line)
f.close()



  • Check existing

if os.path.exists("./myfile.txt"):
    print "Exist file"
else:
    print "Not exist"

if os.path.isdir("./myfolder"):
    print "It is folder"
else:
    print "It is not folder"

if os.path.isfile("./myfile.txt"):
    print "It is file"
else:
    print "It is not file"




  • Try catch

import sys

f = None
try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise
finally:
    if f is not None:
        f.close()






Built-in String Methods

Python includes the following built-in methods to manipulate strings −
SNMethods with Description
1
capitalize()
Capitalizes first letter of string
2
Returns a space-padded string with the original string centered to a total of width columns.
3
Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.
4
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.
5
Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'.
6
endswith(suffix, beg=0, end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.
7
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.
8
Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.
9
Same as find(), but raises an exception if str not found.
10
Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
11
Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
12
Returns true if string contains only digits and false otherwise.
13
Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
14
Returns true if a unicode string contains only numeric characters and false otherwise.
15
Returns true if string contains only whitespace characters and false otherwise.
16
Returns true if string is properly "titlecased" and false otherwise.
17
Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
18
Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.
19
Returns the length of the string
20
Returns a space-padded string with the original string left-justified to a total of width columns.
21
Converts all uppercase letters in string to lowercase.
22
Removes all leading whitespace in string.
23
Returns a translation table to be used in translate function.
24
Returns the max alphabetical character from the string str.
25
Returns the min alphabetical character from the string str.
26
Replaces all occurrences of old in string with new or at most max occurrences if max given.
27
Same as find(), but search backwards in string.
28
Same as index(), but search backwards in string.
29
Returns a space-padded string with the original string right-justified to a total of width columns.
30
Removes all trailing whitespace of string.
31
Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.
32
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.
33
Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.
34
Performs both lstrip() and rstrip() on string
35
Inverts case for all letters in string.
36
Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.
37
Translates string according to translation table str(256 chars), removing those in the del string.
38
Converts lowercase letters in string to uppercase.
39
Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).
40
Returns true if a unicode string contains only decimal characters and false otherwise.


String Formatting Operator

One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family. Following is a simple example −
#!/usr/bin/python

print "My name is %s and weight is %d kg!" % ('Zara', 21) 
When the above code is executed, it produces the following result −
My name is Zara and weight is 21 kg!
Here is the list of complete set of symbols which can be used along with % −
Format SymbolConversion
%ccharacter
%sstring conversion via str() prior to formatting
%isigned decimal integer
%dsigned decimal integer
%uunsigned decimal integer
%ooctal integer
%xhexadecimal integer (lowercase letters)
%Xhexadecimal integer (UPPERcase letters)
%eexponential notation (with lowercase 'e')
%Eexponential notation (with UPPERcase 'E')
%ffloating point real number
%gthe shorter of %f and %e
%Gthe shorter of %f and %E
Other supported symbols and functionality are listed in the following table −
SymbolFunctionality
*argument specifies width or precision
-left justification
+display the sign
<sp>leave a blank space before a positive number
#add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used.
0pad from left with zeros (instead of spaces)
%'%%' leaves you with a single literal '%'
(var)mapping variable (dictionary arguments)
m.n.m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)




Bash Shell Sample


  • Read File

while read line; do
    echo "${line}"
done < test.txt




  • Make list by separating character

for line in `echo "12;34" | tr ";" " "`
do
    echo "${line}"
done

12
34



  • Compare string type

# = : equal
if [ "$a" = "$b" ]; then
    echo "A is equal B"
else
    echo "A is not equal B"
fi

# == : equal
if [ "$a" == "$b" ]; then
    echo "A is equal B"
else
    echo "A is not equal B"
fi

# != : not equal
if [ "$a" != "$b" ]; then
    echo "A is not equal B"
else
    echo "A is equal B"
fi

# < : less
if [[ "$a" < "$b" ]]; then
    echo "A is less than B"
else
    echo "A is greater than B"
fi

if [ "$a" \< "$b" ]; then
    echo "A is less than B"
else
    echo "A is greater than B"
fi

# > : greater
if [[ "$a" > "$b" ]]; then
    echo "A is greater than B"
else
    echo "A is less than B"
fi

if [ "$a" \> "$b" ]; then
    echo "A is greater than B"
else
    echo "A is less than B"
fi


# -z : null
if [ -z "$a" ]; then
    echo "A is null"
else
    echo "A is not null"
fi

# -n : not null
if [ -z "$a" ]; then
    echo "A is not null"
else
    echo "A is null"
fi



  • Compare integer type

# -eq : equal
if [ "$a" -eq "$b" ]; then
    echo "A is equal B"
else
    echo "A is not equal B"
fi

# -ne : not equal
if [ "$a" -ne "$b" ]; then
    echo "A is not equal B"
else
    echo "A is equal B"
fi

# -gt : greater
if ["$a" -gt "$b" ]; then
    echo "A is greater than B"
else
    echo "A is less than B"
fi

# -ge : greater equal
if [ "$a" -ge "$b" ]; then
    echo "A is greater equal than B"
else
    echo "A is less than B"
fi

# -lt : less
if [ "$a" -lt "$b" ]; then
    echo "A is less than B"
else
    echo "A is greater than B"
fi

# -le : less equal
if [ "$a" -le "$b" ]; then
    echo "A is less equal than B"
else
    echo "A is greater than B"
fi

# > : greater
if (( "$a" > "$b" )); then
    echo "A is greater than B"
else
    echo "A is less than B"
fi

# >= : greater equal
if (( "$a" >= "$b" )); then
    echo "A is greater equal than B"
else
    echo "A is less than B"
fi

# < : less
if (( "$a" < "$b" )); then
    echo "A is less than B"
else
    echo "A is greater than B"
fi

# <= : less equal
if (( "$a" <= "$b" )); then
    echo "A is less equal than B"
else
    echo "A is greater than B"
fi



  • Compare float type

$> echo "76.0 < 9.5" | bc
0

$> echo "76.0 > 9.5" | bc
1

$> echo "76.0 >= 91.5" | bc
0

$> echo "76.0 <= 91.5" | bc
1

$> echo "76 > 91.5" | bc
0

$> echo "76 < 91.5" | bc
1

$> echo "76 > 91" | bc
0

$> echo "76 < 91" | bc
1

$> echo "76.0 > 91" | bc
0

$> echo "76.0 < 91" | bc
1


if [[ `echo "76.0 > 9.5" | bc` == 1 ]]; then
    echo "76.0 is greater than 9.5"
else
    echo "76.0 is less than 9.5"
fi

if [[ `echo "76.0 < 91.5" | bc` == 1 ]]; then
    echo "76.0 is less than 91.5"
else
    echo "76.0 is greater than 91.5"
fi



  • Find string in any file

$> grep -r "abcabc" ./*
./views/Picture/Picture.js:             dispatch(abcabcPath(path));