简体   繁体   中英

How i can read the first 10 lines and the last 10 line from filei in python

I have a file and it contain a thousands values so i wont to read only the first 10 and the last 10 values

So I used v.readline() And v.read() but it didn't give me the solution

Iterate over the file using next function.

with open("file") as f:
    lines = [next(f) for x in range(10)]

Simply printing:

res=[]
with open('filename.txt') as inf:
    for count, line in enumerate(inf, 1):
        res.append(str(count))
for r in range(10):
    print(res[r])
for r in range(count-10,count):
    print(res[r])

Alternatively, this saves the output as variable 'result':

res=[]
result=''
with open('filename.txt') as inf:
    for count, line in enumerate(inf, 1):
        res.append(str(count))
for r in range(10):
    result = result + '\n' + res[r]
for r in range(count-10,count):
    result = result + '\n' + res[r]
print(result)

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