+ 1

How do we read in Python file where we need to use readlines and only take up first character from each line ?

That is to read the Python file using readlines function and take up 1st character of each line store it and count the total characters in each line, leaving out \n from the count. Then, output the first character followed by no. of characters in each line. Like a line has "Always use readlines function\n" then output should be A28 , it should count all characters including space but not \n.

12th Jan 2023, 3:45 PM
Jeevesh Kumar Banchhor
6 Answers
+ 2
The following code can be used to read a Python file using the readlines function and take up the first character from each line, store it and count the total characters in each line, leaving out \n from the count. Then, output the first character followed by no. of characters in each line: # open file in read mode file = open("filename.py", "r") # readlines() reads all lines one by one # and stores them as a list of strings lines = file.readlines() # loop through all lines for line in lines: # get first character of each line first_char = line[0] # count total characters in each line (excluding \n) char_count = len(line) - 1 # print first character followed by no. of characters in each line print(first_char + str(char_count))
12th Jan 2023, 3:46 PM
Reza Mardani
Reza Mardani - avatar
+ 8
Reza Mardani , it is not seen as very helpful when we are going to post a ready-made code, as long as the op has not shown his attempt here. it is more helpful to give hints and tips, so that the op has a chance to find a solution by himself.
12th Jan 2023, 4:10 PM
Lothar
Lothar - avatar
+ 2
Lothar Thanks for the advice
12th Jan 2023, 4:12 PM
Reza Mardani
Reza Mardani - avatar
+ 1
Thanks for the help
12th Jan 2023, 3:47 PM
Jeevesh Kumar Banchhor
+ 1
Good Luck :)
12th Jan 2023, 3:48 PM
Reza Mardani
Reza Mardani - avatar
0
Use file. readline() to read a single line from a file readline() to get the first line of the file and store this in a variable first_line .
13th Jan 2023, 9:45 AM
william joe
william joe - avatar