commit
3c90dc2117
42
python.md
42
python.md
|
@ -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(",")
|
||||
|
@ -101,3 +102,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()`.
|
||||
|
|
Loading…
Reference in New Issue