[英]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我有一个文件,它包含数千个值,所以我不会只读取前 10 个和最后 10 个值
So I used v.readline() And v.read() but it didn't give me the solution所以我使用了 v.readline() 和 v.read() 但它没有给我解决方案
Iterate over the file using next function.使用下一个 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':或者,这会将 output 保存为变量“结果”:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.