- Python Built-in Functions
- Python All Built-in Functions
- Python print() Function
- Python input() Function
- Python int() Function
- Python float() Function
- Python len() Function
- Python range() Function
- Python str() Function
- Python ord() Function
- Python chr() Function
- Python ascii() Function
- Python pow() Function
- Python type() Function
- Python List Functions
- Python list() Function
- Python insert() Function
- Python append() Function
- Python extend() Function
- Python pop() Function
- Python remove() Function
- Python reverse() Function
- Python sort() Function
- Python sorted() Function
- Python Dictionary Functions
- Python dict() Function
- Python update() Function
- Python get() Function
- Python keys() Function
- Python setdefault() Function
- Python fromkeys() Function
- Python items() Function
- Python popitem() Function
- Python Tuple Function
- Python tuple() Function
- Python Set Functions
- Python set() Function
- Python frozenset() Function
- Python String Functions
- Python split() Function
- Python join() Function
- Python format() Function
- Python replace() Function
- Python Iterator Functions
- Python iter() Function
- Python min() Function
- Python max() Function
- Python sum() Function
- Python count() Function
- Python index() Function
- Python copy() Function
- Python clear() Function
- Python next() Function
- Python filter() Function
- Python enumerate() Function
- Python zip() Function
- Python reversed() Function
- Python Number Functions
- Python abs() Function
- Python bin() Function
- Python oct() Function
- Python hex() Function
- Python round() Function
- Python divmod() Function
- Python complex() Function
- Python File Handling Functions
- Python open() Function
- Python read() Function
- Python readable() Function
- Python readline() Function
- Python readlines() Function
- Python write() Function
- Python writable() Function
- Python writelines() Function
- Python close() Function
- Python seek() Function
- Python tell() Function
- Python flush() Function
- Python fileno() Function
- Python truncate() Function
- Python Class Functions
- Python object() Function
- Python property() Function
- Python getattr() Function
- Python setattr() Function
- Python hasattr() Function
- Python delattr() Function
- Python classmethod() Function
- Python staticmethod() Function
- Python issubclass() Function
- Python super() Function
- Python Misc Functions
- Python all() Function
- Python any() Function
- Python isatty() Function
- Python bool() Function
- Python callable() Function
- Python globals() Function
- Python locals() Function
- Python dir() Function
- Python id() Function
- Python isinstance() Function
- Python map() Function
- Python repr() Function
- Python slice() Function
- Python vars() Function
- Python Advance Functions
- Python help() Function
- Python hash() Function
- Python breakpoint() Function
- Python bytes() Function
- Python bytearray() Function
- Python memoryview() Function
- Python compile() Function
- Python eval() Function
- Python exec() Function
- Python Tutorial
- Python Tutorial
- Python Examples
- Python Examples
Python read()
The read() function in Python, used to read the content of a file. This function is used to read the whole content or first few bytes of content from the file at once.
Python read() Syntax
The syntax to use read() function in Python is:
fo.read(size)
where fo indicates to the file object or handler. The size must be given in bytes if you want to read first specified number of bytes (characters) from the file. One byte equals to one character.
Note: The size parameter of read() is optional. That is, if you'll not provide any parameter to the read() function, then the whole content of the file gets returned.
Python read() Example
Before proceeding the program, let me create a file say fresherearth.txt with some content. Save this file inside the current directory. Here is the snapshot of the current directory, including the opened newly created file.
Now let's create a program in Python, that uses read() function to read the content of this newly created file:
fo = open("fresherearth.txt", "r") content = fo.read() print(content)
The output produced by above program will be the content available inside the file fresherearth.txt as shown in the snapshot given below, taken when I've executed this program:
In above program, the following two statements:
content = fo.read() print(content)
can also be replaced with single statement as given below:
print(fo.read())
Now let's modify the above program, that receives the name of file from user at run-time. This program also handles error raised when the given file does not exists:
print("Enter the Name of File: ", end="") filename = input() try: fo = open(filename, "r") print("\n----The content of file \"", filename, "\"----", sep="") print(fo.read()) except FileNotFoundError: print("\nThe file \"", filename, "\" doesn't found.", sep="")
Here is its sample run with user input fresherearth.txt:
And here is another sample run with user input none.txt, a non-existing file:
Note: The end= and sep=, both parameters are used to change the default behavior of print(). To learn in detail, refer to its separate tutorial.
Python read() With size Parameter
Now let's create another program, that reads only particular bytes of content from the same file as created earlier. For example, the program given below reads only first 10 bytes from the file:
fo = open("fresherearth.txt", "r") print(fo.read(10))
Here is its sample output:
See, the first 10 characters gets returned from the file. Those 10 characters are:
- H
- e
- y
- !
- (a newline)
- I
- '
- m
- (a space)
- a
Now let me again modify the above program, with the complete package of read() in Python, including handling of invalid inputs:
print("Enter the Name of File: ", end="") filename = input() try: fo = open(filename, "r") print("\n1. Read Whole Content.") print("2. Read Only Specified Number of Bytes.") print("Enter Your Choice (1 or 2): ", end="") try: choice = int(input()) if choice==1: print("\n----The content of file \"", filename, "\"----", sep="") print(fo.read()) elif choice==2: print("\nEnter the Number of Bytes to Read: ", end="") try: nob = int(input()) print("\n----The First ", nob, " characters of file \"", filename, "\"----", sep="") print(fo.read(nob)) except ValueError: print("\nInvalid Input!") except ValueError: print("\nInvalid Input!") except FileNotFoundError: print("\nThe file \"", filename, "\" doesn't found.", sep="")
The sample run of above program with file name input as same file, and choice as 2 to read specified number of bytes, then 15 as number of bytes to read, is shown in the snapshot given below:
« Previous Function Next Function »