Thursday 24 May 2018

Read the contents of a file in python

//To read the entire contents  
with open("filename.txt") as f:
    contents = f.read()
 
//To read line by line 
#!/usr/bin/python

filename = "myfile.txt"
with open( filename ) as f:
    # file read can happen here
    # print "file exists"
    print f.readlines()

with open( filename, "w") as f:
    # print "file write happening here"
    f.write("write something here ") 

No comments:

Post a Comment

list operations in python

How to make each term of an array repeat, with the same terms grouped together? i/p: [A,B,C] o/p: [A,A,A,B,B,B,C,C,C] Solution: >...