1

I'm learning how to manipulate strings in python. I'm currently having an issue using the "startswith()" function. I'm trying to see how many lines start with a specific character I.E "0" but I'm not getting any results. Where did I go wrong? The text file only contains random generated numbers.

random = open("output-onlinefiletools.txt","r")
r = random.read()
#print(len(r))

#small = r[60:79]
#print(r[60:79])
#print(len(r[60:79]))
#print(small)


for line in random:
    line = line.rstrip()
    if line.startswith(1):
        print(line)

2 Answers2

1

You are searching for 1 as an int, and I wouldn't use random as it is not protected but is generally used as part of the random lib; the lines are treated as strings once read thus you need to use startswith on a string and not an int.

myFile = open("C:\Dev\Docs\output-onlinefiletools.txt","r")
r = myFile.read()
# return all lines that start with 0
for line in r.splitlines():
    if line.startswith("0"):
        print(line)

Output:

00000
01123
0000
023478
Madison Courto
  • 1,231
  • 13
  • 25
-2

startwith takes the prefix as argument, in your case it will be line.startswith("0")

ASH
  • 26
  • 4
  • I've tried that as well, in the output terminal its blank with no error code – Tam-Fils Salomon Sep 14 '22 at 20:12
  • @Tam-FilsSalomon This may mean that no line starts with 0, can you ensure that at least one verifying the condition just for test – ASH Sep 14 '22 at 20:15
  • @Tam-FilsSalomon Did you actually try *`"0"`* or just `0`? Those quotes matter a lot. (Edit: for anyone who missed it, the question code had `.startwith(1)` instead of `.startswith("1")`.) – mtraceur Sep 14 '22 at 20:15
  • I later discovered that the txt file got corrupted, smh – Tam-Fils Salomon Sep 14 '22 at 20:49