Python Program to Read a File

This article covers a program in Python that reads a file, entered by user at run-time of the program.

Read a File in Python

The question is, write a Python program to read a file. The name of file must be received by user at run-time. The program given below is its answer:

print("Enter the Name of a File to Read: ", end="")
fileName = input()

fileHandle = open(fileName, "r")
content = fileHandle.read()
print("\n----File Contains----")
print(content)

The snapshot given below shows the sample run of above Python program, with user input codescracker.txt as name of file to read

python program read a file

The file codescracker.txt has to be available inside the current directory, the directory where the above Python's source code is saved. Here is the snapshot of the current directory, with opened file, in my case:

python program read file example

Note - The read() method is used to read the whole content of a file.

Note - The open() method is used to open a file. To learn in detail, refer to its separate tutorial.

Note - The end parameter used in above program, to skip insertion of an automatic newline using print().

Read Text File Line by Line in Python

This program does the same job as of previous program, that is to read a file. But this program is created in a way to read a file line by line. That is, all the lines of a file is initialized to a variable say lines in the form of list items or elements, using the readlines() method.

print("Enter the Name of a File to Read: ", end="")
fileName = input()

fileHandle = open(fileName, "r")
lines = fileHandle.readlines()
print("\n----File Contains----")
for line in lines:
    print(line, end="")

This program produces the same output as of previous program.

Note - The readlines() method returns the content of a file in the form of list, where each elements refers to the line of file. The detailed description about the method, is provided in its separate tutorial.

Same Program in Other Languages

Python Online Test


« Previous Program Next Program »