Python File handling example? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Python File handling example?

11th Feb 2017, 2:46 PM
Kinoshanth Sivakumar
Kinoshanth Sivakumar - avatar
3 Answers
+ 3
To open a text file, use: fh = open("hello.txt", "r") To read a text file, use: fh = open("hello.txt","r") print fh.read() To read one line at a time, use: fh = open("hello".txt", "r") print fh.readline() To read a list of lines use: fh = open("hello.txt.", "r") print fh.readlines() To write to a file, use: fh = open("hello.txt","w") write("Hello World") fh.close() To write to a file, use: fh = open("hello.txt", "w") lines_of_text = ["a line of text", "another line of text", "a third line"] fh.writelines(lines_of_text) fh.close() To append to file, use: fh = open("Hello.txt", "a") write("Hello World again") fh.close To close a file, use fh = open("hello.txt", "r") print fh.read() fh.close()
11th Feb 2017, 2:50 PM
EMMANUEL NUOTAH TUONUO DERY
EMMANUEL NUOTAH TUONUO DERY - avatar
+ 2
you can you the with statement which is a good practice: with open('file.txt', 'w') as f: f.write('Hello world!') note:if you use with you dont have to close the file (f.close()) with does it for you when the statement is done
11th Feb 2017, 3:58 PM
TheoVal
TheoVal - avatar
+ 1
filename = "hello.txt" file = open(filename, "r") for line in file: print line,
11th Feb 2017, 2:49 PM
EMMANUEL NUOTAH TUONUO DERY
EMMANUEL NUOTAH TUONUO DERY - avatar