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)
CodePudding user response:
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
CodePudding user response:
startwith takes the prefix as argument, in your case it will be line.startswith("0")