- 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 −
SN | Methods 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 Symbol | Conversion |
---|---|
%c | character |
%s | string conversion via str() prior to formatting |
%i | signed decimal integer |
%d | signed decimal integer |
%u | unsigned decimal integer |
%o | octal integer |
%x | hexadecimal integer (lowercase letters) |
%X | hexadecimal integer (UPPERcase letters) |
%e | exponential notation (with lowercase 'e') |
%E | exponential notation (with UPPERcase 'E') |
%f | floating point real number |
%g | the shorter of %f and %e |
%G | the shorter of %f and %E |
Other supported symbols and functionality are listed in the following table −
Symbol | Functionality |
---|---|
* | 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. |
0 | pad 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.) |