Saturday, April 25, 2020

Python: Reading File


 

Python programming language is simple to use. Using python, we can simply read a text file using open() function. open() function takes two arguments. Through first argument, we specify the file name. Via second argument, we specify the mode to open the file. Available modes are:

CharacterMeaning
'r'open for reading (default)
'w'open for writing, truncating the file first
'x'open for exclusive creation, failing if the file already exists
'a'open for writing, appending to the end of the file if it exists
'b'binary mode
't'text mode (default)
'+'open for updating (reading and writing)

Let's read a simple text file using following few lines of code:

file = open("location/to/file.txt",'r')
for line in file:
    print(line)
file.close() 

In this code, variable 'file' is used to store data from the file. A for loop was used to read file line by line. Variable 'line' is used to represent each line during the loop. During the loop, each line inside the file were printed using built-in print() function. After the reading completed, opened file was closed using close() function.
This can also be done in following way:

with open("location/to/file.txt",'r') as file:
    for line in file:
        print(line)

The advantage of above code is that, it automatically close the file once the processing is done.




No comments:

Post a Comment

Working with Biological data: part 1

Fasta file is a text-based file used to store nucleotide or protein sequences.Inside the file, each sequence begins with a single line d...