Home > Net >  how do you get the length of a line in a text file?
how do you get the length of a line in a text file?

Time:12-30

line = initDict.readline()
  while line:
    line = initDict.readline()
    print(line)
    if len(line) == 5: # <<< problem
      line = initDict.readline()
      transfer.append(line)

I'm trying to get the length of the line, not the line number.

Input:

1
22
33335
4444
55555

Output:

55555 (line 5)

(where’s 33335? (line 3))

CodePudding user response:

You can use the len

# Open the file in read mode
with open('file.txt', 'r') as file:
  # Read the first line
  line = file.readline()
  # Get the length of the line
  line_length = len(line)
  # Print the length of the line
  print(line_length)

CodePudding user response:

You are checking the length. That's not the problem.

The real problems are that, first, the lines you're reading include the line terminator character. Instead of '33335', you're getting '33335\n', which is 6 characters. Instead of '4444', you're getting '4444\n', which is 5 characters.

The second problem is that after you read a line and find it has 5 characters, you read another line and store that line instead of the one that actually had 5 characters. '4444\n' passes the check, but you append '55555\n' instead (or maybe it's '55555' if your file doesn't end with a line terminator).

You need to remove the trailing line break, and store the lines that match the check instead of the lines immediately after:

for line in initDict:
    line = line.removesuffix('\n')
    if len(line) == 5:
        transfer.append(line)

CodePudding user response:

Here is a code to show the lines that have 5 digits.

with open("test.txt", "r") as initDict:
    lines = initDict.readlines()

for line in lines:
    if len(line) > 5:
        print(line)

and here is the code to show each line has how many digits:

with open("test.txt", "r") as initDict:
    lines = initDict.readlines()
    for line in lines:
        print(len(line.rstrip()))
  • Related