Update python.md (#1281)

Update python.md
This commit is contained in:
Rico Sta. Cruz 2019-12-18 13:41:39 +11:00 committed by GitHub
commit 3c90dc2117
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 42 additions and 0 deletions

View File

@ -58,6 +58,7 @@ category: Python
string.replace("-", " ") string.replace("-", " ")
",".join(list) ",".join(list)
"hi {0}".format('j') "hi {0}".format('j')
"hi {name}" # same as "hi {}".format('name')
str.find(",") str.find(",")
str.index(",") # same, but raises IndexError str.index(",") # same, but raises IndexError
str.count(",") str.count(",")
@ -101,3 +102,44 @@ category: Python
expr.match(...) expr.match(...)
expr.sub(...) 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()`.