简体   繁体   English

我如何从 python 中的 filei 读取前 10 行和最后 10 行

[英]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.

相关问题 如何删除 python 中的最后一行以将其保持在 10 行 - How to remove the last line in python to keep it at exactly 10 lines 在Python中,如何使用“strip()for line in file”格式从文件中读取前x行? - In Python, how can I read just the first x lines from a file using the “strip() for line in file” format? Python:如何从10个清单中获得前5个或后5个? - Python: How to get first 5 or last 5 from list of 10? 如何使用 Python 仅打印 csv 文件的前 10 行? - How do I print only the first 10 lines from a csv file using Python? Python 从 Outlook 读取最后 10 封电子邮件 - Python read last 10 emails from Outlook 如何从python中文件的最后一行读取第一个字符 - How to read a first character from the last line of a file in python 读取文件的前 10 行; 如果更短只阅读那些行 - Read First 10 Lines in a File; If Shorter Only Read Those Lines 如何使用Matplotlib在python中定义和绘制10 * 10数组? - how can I define and plot an 10*10 array in python with Matplotlib? 如何从python中的字符串中删除最后2行? - How can I remove last 2 lines from a string in python? 如何将一列的前 10 个值分配给 pandas dataframe 中另一列的前 10 行? - How can I assign first 10 values from one column, to first 10 rows of another column in pandas dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM