1

I am trying to find the characters in one specific line of my code. Say the line is 4.

My file consists of:

1. randomname
2. randomname
3. 
4. 34
5. 12202018

My code consists of:

with open('/Users/eviemcmahan/PycharmProjects/eCYBERMISSION/eviemcmahan', 'r') as my_file:

data = my_file.readline(4)
characters = 0

for data in my_file:
    words = data.split(" ")
    for i in words:
        characters += len(i)

print(characters)

I am not getting an error, I am just getting the number "34"

I would appreciate any help on how to get a correct amount of characters for line 4.

EMCMAHE
  • 55
  • 1
  • 8
  • just remove the `data.split(" ")` part. This will keep all the characters – ma3oun Dec 21 '18 at 14:08
  • why are iterating over the lines in the file.. are you supposed to get the only the fourth line?? – Anwarvic Dec 21 '18 at 14:09
  • What do you think `my_file.readline(4)` does? And can you clarify exactly what you're looking for? The number of characters on a given line? – glibdud Dec 21 '18 at 14:17
  • @glibdud I didn't realize 'my_file.readline(4)' only read the fourth character. And yes, I am trying to find the number of characters on a given line. – EMCMAHE Dec 21 '18 at 16:36

1 Answers1

0

my_file.readline(4) does not read the 4th line, instead reads the next line but only the 4 firsts characters. To read a specific line you need to, for example, read all the lines and put them in a list. Then is easy to get the line you want. You could also read line by line and stop whenever you find yourself in the line you desired.

Going with the first approach and using the count method of strings, it is straight-forward to count any character at a specific line. For example:

line_number = 3 # Starts with 0
with open('test.txt', 'r') as my_file:
  lines = my_file.readlines() # List containing all the lines as elements of the list
print(lines[line_number ].count('0')) # 0
print(lines[line_number ].count('4')) # 2
b-fg
  • 3,959
  • 2
  • 28
  • 44
  • Thanks! How do I get it to count the characters because the results are producing: 0 and 1, not the amount of characters. Thx again!! – EMCMAHE Dec 21 '18 at 16:30
  • For the total amount do `len(lines[line_number])` – b-fg Dec 21 '18 at 16:56