File handling in Python requires no importing of modules.
Instead we can use the built-in object “file”. That object provides basic functions and methods necessary to manipulate files by default. Before you can read, append or write to a file, you will first have to it using Python’s built-in open() function. In this post I will describe how to use the different methods of the file object.
The open() function is used to open files in our system, the filename is the name of the file to be opened. The mode indicates, how the file is going to be opened “r” for reading, “w” for writing and “a” for a appending. The open function takes two arguments, the name of the file and and the mode for which we would like to open the file. By default, when only the filename is passed, the open function opens the file in read mode.
This small script, will open the (hello.txt) and print the content. This will store the file information in the file object “filename”.
filename = "hello.txt" file = open(filename, "r") for line in file: print line,
The read functions contains different methods, read(),readline() and readlines()
read() #return one big string readline #return one line at a time read-lines #returns a list of lines
This method writes a sequence of strings to the file.
write () #Used to write a fixed sequence of characters to a file writelines() #writelines can write a list of strings.
The append function is used to append to the file instead of overwriting it. To append to an existing file, simply open the file in append mode (“a”):
When you’re done with a file, use close() to close it and free up any system resources taken up by the open file
File Handling Examples
Let’s show some examples
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()
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.