OSDN Git Service

Regular updates
[twpd/master.git] / python.md
index 1821eb0..f885717 100644 (file)
--- a/python.md
+++ b/python.md
@@ -11,7 +11,7 @@ category: Python
     list[:-1]  # returns all but the last element
     
     list[i] = val
-    list[i:j] = otherlist  # replace ith to jth element with otherlist
+    list[i:j] = otherlist  # replace ith to jth-1 elements with otherlist
     del list[i:j]
 
     list.append(item)
@@ -58,6 +58,7 @@ category: Python
     string.replace("-", " ")
     ",".join(list)
     "hi {0}".format('j')
+    "hi {name}" # same as "hi {}".format('name')
     str.find(",")
     str.index(",")   # same, but raises IndexError
     str.count(",")
@@ -72,6 +73,18 @@ category: Python
     str.strip()
 
     str.islower()
+    
+    /* escape characters */
+    >>> 'doesn\'t'  # use \' to escape the single quote...
+        "doesn't"
+    >>> "doesn't"  # ...or use double quotes instead
+        "doesn't"
+    >>> '"Yes," they said.'
+        '"Yes," they said.'
+    >>> "\"Yes,\" they said."
+        '"Yes," they said.'
+    >>> '"Isn\'t," they said.'
+        '"Isn\'t," they said.'
 
 ### Casting
 
@@ -101,3 +114,44 @@ category: Python
     expr.match(...)
     expr.sub(...)
 
+## File manipulation
+    
+### Reading
+
+```py
+file = open("hello.txt", "r") # open in read mode 'r'
+file.close() 
+
+print(file.read())  # read the file 
+print fh.readline() # Reading line by line
+```
+
+### Writing (overwrite)
+
+```py
+file = open("hello.txt", "w") # open in write mode 'w'
+write("Hello World")
+
+text_lines = ["First line", "Second line", "Last line"] 
+file.writelines(text_lines)
+
+file.close()
+```
+
+### Writing (append)
+
+```py
+file = open("Hello.txt", "a") # open in append mode
+write("Hello World again")  
+file.close()
+```
+
+### Context manager
+
+```py
+with open("welcome.txt", "r") as file:
+    # 'file' refers directly to the "welcome.txt"
+   data = file.read()
+```
+
+It closes the file automatically, no need for `file.close()`.