Open file for reading
f = open ("myfile.txt", "r")
if f.mode == "r":
data = f.read() ## read the whole file
line = f.readline() ## read a line
Open file for writing, the regular way
f = open ("myfile.txt", "w")
for i in range (10):
f.write ( i, "line" )
# append more lines
f = open ("myfile.txt", "a")
f.write ("That's all")
f.close()
Be a pythonist!
data = open ("myfile.txt").read() ## return whole file as one single string
data = open ("myfile.txt").readline() ## return one line as a string
data = open ("myfile.txt").readlines() ## return whole file as list of strings, with '\n'
f = "myfile.txt"
with open( f ) as fh:
lines = list( map( str.rstrip, fh.readlines() ))
No comments:
Post a Comment