我们有一个很大的原始数据文件,我们想把它修剪成指定的大小。
如何在python中获取文本文件的前N行?所使用的操作系统对实现有任何影响吗?
我们有一个很大的原始数据文件,我们想把它修剪成指定的大小。
如何在python中获取文本文件的前N行?所使用的操作系统对实现有任何影响吗?
当前回答
如果您有一个非常大的文件,并假设您希望输出为numpy数组,则使用np。Genfromtxt将冻结您的计算机。以我的经验来看,这样好多了:
def load_big_file(fname,maxrows):
'''only works for well-formed text file of space-separated doubles'''
rows = [] # unknown number of lines, so use list
with open(fname) as f:
j=0
for line in f:
if j==maxrows:
break
else:
line = [float(s) for s in line.split()]
rows.append(np.array(line, dtype = np.double))
j+=1
return np.vstack(rows) # convert list of vectors to array
其他回答
Python 3:
with open("datafile") as myfile:
head = [next(myfile) for x in range(N)]
print(head)
Python 2:
with open("datafile") as myfile:
head = [next(myfile) for x in xrange(N)]
print head
下面是另一种方法(Python 2和3都是):
from itertools import islice
with open("datafile") as myfile:
head = list(islice(myfile, N))
print(head)
fname = input("Enter file name: ")
num_lines = 0
with open(fname, 'r') as f: #lines count
for line in f:
num_lines += 1
num_lines_input = int (input("Enter line numbers: "))
if num_lines_input <= num_lines:
f = open(fname, "r")
for x in range(num_lines_input):
a = f.readline()
print(a)
else:
f = open(fname, "r")
for x in range(num_lines_input):
a = f.readline()
print(a)
print("Don't have", num_lines_input, " lines print as much as you can")
print("Total lines in the text",num_lines)
我想通过读取整个文件来处理小于n行的文件
def head(filename: str, n: int):
try:
with open(filename) as f:
head_lines = [next(f).rstrip() for x in range(n)]
except StopIteration:
with open(filename) as f:
head_lines = f.read().splitlines()
return head_lines
这要归功于约翰·拉·鲁伊和伊莲·伊利耶夫。使用异常句柄函数以获得最佳性能
修改1:感谢FrankM的反馈,处理文件存在和读取权限我们可以进一步增加
import errno
import os
def head(filename: str, n: int):
if not os.path.isfile(filename):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), filename)
if not os.access(filename, os.R_OK):
raise PermissionError(errno.EACCES, os.strerror(errno.EACCES), filename)
try:
with open(filename) as f:
head_lines = [next(f).rstrip() for x in range(n)]
except StopIteration:
with open(filename) as f:
head_lines = f.read().splitlines()
return head_lines
您可以使用第二个版本,也可以使用第一个版本,稍后再处理文件异常。从性能的角度来看,检查是快速的,而且大部分是免费的
#!/usr/bin/python
import subprocess
p = subprocess.Popen(["tail", "-n 3", "passlist"], stdout=subprocess.PIPE)
output, err = p.communicate()
print output
这个方法对我很有效
没有特定的方法来读取文件对象暴露的行数。
我想最简单的方法是:
lines =[]
with open(file_name) as f:
lines.extend(f.readline() for i in xrange(N))