Merge pull request #1437 from rb-x/rb-x-patch-python
This commit is contained in:
commit
d42235b255
18
python.md
18
python.md
|
@ -58,7 +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')
|
f"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(",")
|
||||||
|
@ -121,16 +121,19 @@ category: Python
|
||||||
```py
|
```py
|
||||||
file = open("hello.txt", "r") # open in read mode 'r'
|
file = open("hello.txt", "r") # open in read mode 'r'
|
||||||
file.close()
|
file.close()
|
||||||
|
```
|
||||||
|
|
||||||
print(file.read()) # read the file
|
```py
|
||||||
print fh.readline() # Reading line by line
|
print(file.read()) # read the entire file and set the cursor at the end of file
|
||||||
|
print file.readline() # Reading one line
|
||||||
|
file.seek(0, 0) # place the cursor at the beggining of the file
|
||||||
```
|
```
|
||||||
|
|
||||||
### Writing (overwrite)
|
### Writing (overwrite)
|
||||||
|
|
||||||
```py
|
```py
|
||||||
file = open("hello.txt", "w") # open in write mode 'w'
|
file = open("hello.txt", "w") # open in write mode 'w'
|
||||||
write("Hello World")
|
file.write("Hello World")
|
||||||
|
|
||||||
text_lines = ["First line", "Second line", "Last line"]
|
text_lines = ["First line", "Second line", "Last line"]
|
||||||
file.writelines(text_lines)
|
file.writelines(text_lines)
|
||||||
|
@ -142,7 +145,7 @@ file.close()
|
||||||
|
|
||||||
```py
|
```py
|
||||||
file = open("Hello.txt", "a") # open in append mode
|
file = open("Hello.txt", "a") # open in append mode
|
||||||
write("Hello World again")
|
file.write("Hello World again")
|
||||||
file.close()
|
file.close()
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -150,8 +153,9 @@ file.close()
|
||||||
|
|
||||||
```py
|
```py
|
||||||
with open("welcome.txt", "r") as file:
|
with open("welcome.txt", "r") as file:
|
||||||
# 'file' refers directly to the "welcome.txt"
|
# 'file' refers directly to "welcome.txt"
|
||||||
data = file.read()
|
data = file.read()
|
||||||
|
|
||||||
|
# It closes the file automatically at the end of scope, no need for `file.close()`.
|
||||||
```
|
```
|
||||||
|
|
||||||
It closes the file automatically, no need for `file.close()`.
|
|
||||||
|
|
Loading…
Reference in New Issue