+ 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.
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))
+ 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.
+ 2
Lothar
Thanks for the advice
+ 1
Thanks for the help
+ 1
Good Luck :)
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 .