How to make Python delete lines containing strings over a maximum character limit?

Viewed 57

I have a list of URLs in a text file. Some of them are short, while others are very long. I'd like to have Python go through this text file and delete all lines containing strings that go over the maximum character limit. How can I do something like that in Python?

4 Answers

you can use open command like:

f = open("textfile.txt", "r")

while "r" stands for reading the file

then store lines in another variable like:

lines = f.readlines()

and you have an array of lines.

If you've imported the file and have the URLs in a list... I would use a for loop to go over each URL in the file (for URL in list:), then an if statement (if len(URL) >= 100: list.remove(URL)) The len function for strings counts all characters in the string. hope this makes sense!

with open(txtFile.txt, r) as file:
    newFile = file.readlines()

for entryNumber in range(0, len(newFile)):
    if len(newFile[entryNumber]) > limitNumber:
        del newFile[entryNumber]

This will delete all link entries that are above the character limit

#If websites are in same line separated by commas
with open('websites.txt','r') as websites:
    for w in websites.read().split(','):
        if len(w) < 17:
            print(w)

#If websites are in separate lines
with open('websites.txt','r') as websites:
    for w in websites.readlines():
        if len(w) < 17:
            print(w)
Related