Update formatting
This commit is contained in:
parent
d5623e46fb
commit
947d9c3135
49
python.md
49
python.md
|
@ -102,35 +102,44 @@ category: Python
|
|||
expr.match(...)
|
||||
expr.sub(...)
|
||||
|
||||
### File manipulation
|
||||
## File manipulation
|
||||
|
||||
# Reading
|
||||
### Reading
|
||||
|
||||
file = open("hello.txt", "r") #open the file in readmode 'r'
|
||||
file.close()
|
||||
```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
|
||||
print(file.read()) # read the file
|
||||
print fh.readline() # Reading line by line
|
||||
```
|
||||
|
||||
# Writing ( Overwrite the previous content ! )
|
||||
### Writing (overwrite)
|
||||
|
||||
file = open("hello.txt","w") # open the fil in write mode
|
||||
write("Hello World")
|
||||
```py
|
||||
file = open("hello.txt", "w") # open in write mode 'w'
|
||||
write("Hello World")
|
||||
|
||||
text_lines = ["First line", "Second line", "a third and last line"]
|
||||
file.writelines(text_lines) # write the 3 line above inside hello.txt
|
||||
text_lines = ["First line", "Second line", "Last line"]
|
||||
file.writelines(text_lines)
|
||||
|
||||
file.close()
|
||||
file.close()
|
||||
```
|
||||
|
||||
# Append File
|
||||
### Writing (append)
|
||||
|
||||
file = open("Hello.txt", "a") #open file in append mode
|
||||
write("Hello World again")
|
||||
file.close()
|
||||
```py
|
||||
file = open("Hello.txt", "a") # open in append mode
|
||||
write("Hello World again")
|
||||
file.close()
|
||||
```
|
||||
|
||||
# Context Manager
|
||||
### Context manager
|
||||
|
||||
with open("welcome.txt" ,"r") as file: # file refer directly to the "welcome.txt" , mode = r , w , a
|
||||
data = file.read()
|
||||
# it close the file automatically no need for file.close()
|
||||
```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