Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

readlines from file python

f = open("file.txt", 'r')
print(f.readlines())  # array of file lines
Comment

readlines

'''write a program using python functions to count the number of 
lines beginning with “a” in “file.txt” '''

source code:

def counta() :
    f=open('file.txt')
    p=f.readlines()
    count=0
    for i in p:
        if i[0].upper()=='A':
            count+=1
    print(" number of lines initiating with word a",count)
counta()

'''file.txt'''
The life that I have
Is all that I have
And the life that I have
Is yours
The love that I have
Of the life that I have
Is yours and yours and yours.
A sleep I shall have
A rest I shall have
Yet death will be but a pause
For the peace of my years
In the long green grass
Will be yours and yours and yours.

-+-+--+-++-+-+-+-+-+--+-+-++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

output:
number of lines initiating with word a 3





Comment

The readlines() method returns

# The readlines() method returns
# Answer: A list of lines
Comment

PREVIOUS NEXT
Code Example
Python :: extract coordinate values in xarray 
Python :: run all python files in a directory in windows 
Python :: turtle graphics documentation 
Python :: discord.py permissions 
Python :: python for loop index 
Python :: What will be the output of the following program? 
Python :: wifite2 
Python :: make sure it only has letters and numbers python 
Python :: matrix multiplication nupy 
Python :: python decorator 
Python :: python towers of hanoi recursive 
Python :: pyspark read from redshift 
Python :: how to find the longest string python 
Python :: how to check a string is empty in python 
Python :: how to check if a variable holds a class reference in python 
Python :: matrix diagonal sum leetcode in Python 
Python :: python set python key default 
Python :: uninstall every package in environment 
Python :: how to get the length of a string in python 
Python :: read list stored as a string with pandas read csv 
Python :: uppercase python 
Python :: django unique validator 
Python :: string python 
Python :: continue and break in python 
Python :: count number of objects django template 
Python :: find & replace in csv file 
Python :: get first element of array python 
Python :: print format round python 
Python :: python common elements in two arrays 
Python :: python clear stdout 
ADD CONTENT
Topic
Content
Source link
Name
2+8 =