简体   繁体   中英

Remove lines by line number in python

I have a normal text file (.txt) and want to make it into a string for easy processing. The file has 80 lines, but I don't want to include lines 1-4 and 74-80. Right now I have the full file including those lines.

with open("textfile.txt") as file:
    text = file.read()
    clean_text = ""
    for line in text:
        clean_text += line.replace("\n", " ")
print(clean_text)

This code only replaces the newline characters by a space, but I also want to exclude the lines I previously stated.

You could add a counter to the program and check if that iteration isn't in the list. An example could be like this:

with open("textfile.txt") as file:
    ignore_lines = [1,2,3,4,74,75,76,77,78,79,80]
    text = file.readlines()
    clean_text = ""
    inter = 1
    for line in text:
        if inter not in ignore_lines:
            clean_text += line.replace("\n", " ")
        inter += 1
print(clean_text)

You can simply do:

with open("textfile.txt", "r") as file:
    text = ''.join([line.replace("\n", " ") for line in file.readlines()[5:74]])

Of course assuming its 74-80 instead of 84-80.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM