简体   繁体   中英

Python - readlines

Is there a way I can just have python read lines and only use the first 10 characters and then assign them to a variable?

Remove_example= 'example'
Remove_at= '@'
#Remove_Agent='

filepath = 'Older WinCollect Agents on Version 728.txt'
with open(filepath) as fp:
   line = fp.readline()
   print(line[0][10])
   cnt = 1
   while line:
       print("Line {}: {}".format(cnt, line.strip(),).replace(str(Remove_example),'').replace(str(Remove_at),''))
       line = fp.readline()
       cnt += 1

I don't want to put static remove line variables

def get_line_fronts(filepath: str) -> list:
    """Get list of first 10 characters in each line in a file."""
    line_fronts = []
    with open(filepath, "r") as fh:
        for line in fh:
            line_fronts.append(line[:10])
    return line_fronts


filepath = 'Older WinCollect Agents on Version 728.txt'
for line_front in get_line_fronts(filepath):
    # do whatever

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