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.
- Python Programming – File Functions
- Python Programming – Operations on Files
- Python Programming – File Processing
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