Update python.md

Adding file managing cheatsheet
This commit is contained in:
Riadh Bch 2019-11-24 18:19:00 +01:00 committed by GitHub
parent 1ed003c8f4
commit d5623e46fb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 33 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,35 @@ category: Python
expr.match(...) expr.match(...)
expr.sub(...) expr.sub(...)
### File manipulation
# Reading
file = open("hello.txt", "r") #open the file in readmode 'r'
file.close()
print(file.read()) # read the file
print fh.readline() # Reading line by line
# Writing ( Overwrite the previous content ! )
file = open("hello.txt","w") # open the fil in write mode
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
file.close()
# Append File
file = open("Hello.txt", "a") #open file in append mode
write("Hello World again")
file.close()
# 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()