파일에서 특정 행(행 번호별)을 읽는 방법
사용하고 있습니다.for
을 사용하여 단, 특정 행(를 들어 행)만 싶습니다. 「」 「」회선#26
★★★★★★★★★★★★★★★★★」#30
이를 실현하기 위한 빌트인 기능이 있습니까?
읽을 파일이 큰 경우 메모리의 전체 파일을 한 번에 읽지 않으려면 다음을 수행하십시오.
fp = open("file")
for i, line in enumerate(fp):
if i == 25:
# 26th line
elif i == 29:
# 30th line
elif i > 29:
break
fp.close()
:i == n-1
★★★★★★★★★★★★★★★★의 경우n
【1】
Python 2.6 이후:
with open("file") as fp:
for i, line in enumerate(fp):
if i == 25:
# 26th line
elif i == 29:
# 30th line
elif i > 29:
break
즉답:
f=open('filename')
lines=f.readlines()
print lines[25]
print lines[29]
또는 다음과 같이 입력합니다.
lines=[25, 29]
i=0
f=open('filename')
for line in f:
if i in lines:
print i
i+=1
많은 행을 추출하기 위한 보다 우아한 솔루션이 있습니다.linecache(stackoverflow.com의 이전 질문인 "how to jump to signific line in a long text file?" 참조).
위에 링크된 python 문서를 인용합니다.
>>> import linecache
>>> linecache.getline('/etc/passwd', 4)
'sys:x:3:3:sys:/dev:/bin/sh\n'
변경합니다.4
원하는 회선 번호에 도달하면 바로 켜집니다.카운트가 제로 베이스이므로 4는 다섯 번째 행을 가져옵니다.
파일이 매우 커서 메모리로 읽을 때 문제가 발생할 수 있다면 @Alok의 조언을 받아 enumerate()를 사용하는 것이 좋습니다.
결론:
fileobject.readlines()
★★★★★★★★★★★★★★★★★」for line in fileobject
작은 파일을 위한 빠른 솔루션입니다.linecache
하다이것은, 많은 파일을 반복해 읽기에 꽤 빠릅니다.- @Alok의 조언에 따라 매우 크고 메모리에 들어가지 않는 파일에 사용합니다.파일이 순차적으로 읽기 때문에 이 방법을 사용하면 속도가 느려질 수 있습니다.
다른 솔루션을 제공하기 위해:
import linecache
linecache.getline('Sample.txt', Number_of_Line)
빠르고 쉬운 작업이 되었으면 합니다. :)
빠르고 콤팩트한 접근방식은 다음과 같습니다.
def picklines(thefile, whatlines):
return [x for i, x in enumerate(thefile) if i in whatlines]
있는 오브젝트 「파일」을 할 수 있습니다.thefile
파일 스트림 중 어느 및 제로 인덱스 ( 「」, 「」, 「」, 「」, 「」, 「」, 「」의 어느 쪽인가 하면, 발신자에게 통지합니다).whatlines
메모리 용량이 적고 속도가 적당한 목록을 반환합니다.반환되는 회선 수가 많은 경우 제너레이터를 사용하는 것이 좋습니다.
def yieldlines(thefile, whatlines):
return (x for i, x in enumerate(thefile) if i in whatlines)
에만 적합합니다.입니다.단 한 가지 차이점은 대괄호가 아닌 둥근 괄호를 사용하는 것입니다.return
문장, 목록 이해 및 생성자 식을 만듭니다.
게다가 이러한 함수는, 「행」이나 「파일」에 대해서는 언급하고 있습니다만, 보다 일반적인 것입니다.이 함수는, 오픈 파일인지 다른 파일인지 어떤지에 관계없이, 어느 반복 가능한 기능에서도 동작해, 진척된 항목 번호에 근거해 항목의 리스트(또는 생성기)를 반환합니다.그래서 저는 좀 더 적절한 일반 이름을 사용하는 것이 좋습니다;-)
완성도를 높이기 위해 여기 한 가지 옵션이 더 있습니다.
일반적으로 시퀀스의 일부를 포함하는 개체 슬라이스입니다.슬라이스는 variable_name[1:3:5]와 같이 여러 개의 콜론이 지정되면 숫자 사이에 콜론이 있는 첨자 표기법 []을 사용하여 생성됩니다.괄호(서브스크립트) 표기법에서는 슬라이스 오브젝트를 내부적으로 사용합니다(또는 이전 버전에서는 __getslice_() 및 __setslice_()).
에 직접 할 수 , 리터레이터는 .itertools
패키지에는 교환 기능이 포함되어 있습니다.
from itertools import islice
# print the 100th line
with open('the_file') as lines:
for line in islice(lines, 99, 100):
print line
# print each third line until 100
with open('the_file') as lines:
for line in islice(lines, 0, 100, 3):
print line
이 기능의 또 다른 장점은 이 기능이 끝까지 반복기를 읽지 않는다는 것입니다.따라서 보다 복잡한 작업을 수행할 수 있습니다.
with open('the_file') as lines:
# print the first 100 lines
for line in islice(lines, 100):
print line
# then skip the next 5
for line in islice(lines, 5):
pass
# print the rest
for line in lines:
print line
그리고 원래의 질문에 답하려면:
# how to read lines #26 and #30
In [365]: list(islice(xrange(1,100), 25, 30, 4))
Out[365]: [26, 30]
7호선을 원하시면
line = openfiles.txt", "r".readlines()[7]
파일 읽기는 놀라울 정도로 빠릅니다.100MB 파일을 읽는 데 걸리는 시간은 0.1초 미만입니다(내 기사 Python을 사용한 파일 읽기 및 쓰기 참조).따라서 이 내용을 완전히 읽은 후 한 줄로 작업해야 합니다.
대부분의 답은 틀리지 않고 나쁜 스타일입니다.파일이 다시 닫히므로 파일을 여는 작업은 항상 수행해야 합니다.
따라서 다음과 같이 해야 합니다.
with open("path/to/file.txt") as f:
lines = f.readlines()
print(lines[26]) # or whatever you want to do with this line
print(lines[30]) # or whatever you want to do with this line
대용량 파일
대량의 파일이 있어 메모리 사용량이 우려되는 경우 한 줄씩 처리할 수 있습니다.
with open("path/to/file.txt") as f:
for i, line in enumerate(f):
pass # process line i
이 중 몇 가지는 훌륭하지만, 훨씬 간단하게 실시할 수 있습니다.
start = 0 # some starting index
end = 5000 # some ending index
filename = 'test.txt' # some file we want to use
with open(filename) as fh:
data = fin.readlines()[start:end]
print(data)
리스트 슬라이스를 사용하여 파일 전체를 로드하지만 대부분의 시스템은 메모리 사용량을 적절하게 최소화하고 위의 방법보다 고속이며 10G 이상의 데이터 파일로 작동합니다.행운을 빕니다.
파일 「」의 .file
엄밀하게 구성되어 의 길이가 것을 합니다).l
에는, 을 할 수 .n
- - 줄
with open(file) as f:
f.seek(n*l)
line = f.readline()
last_pos = f.tell()
면책사항 이 방법은 길이가 같은 파일에만 적용됩니다.
파일 내의 지정된 바이트에 읽기 헤드를 배치하는 seek() 호출을 수행할 수 있습니다.읽고 싶은 행 앞에 몇 바이트(문자)가 기입되어 있는지를 정확하게 알지 않는 한, 이것은 도움이 되지 않습니다.파일의 형식이 엄밀하게 설정되어 있는 경우(각 행이 X 바이트 수입니까?), 또는 정말로 속도를 높이고 싶은 경우는, 스스로 문자수를 셀 수 있습니다(줄 바꿈 등 보이지 않는 문자를 포함할 필요가 있습니다.
그렇지 않은 경우, 여기에서 이미 제안된 여러 솔루션 중 하나에 따라 원하는 행보다 먼저 모든 행을 읽어야 합니다.
def getitems(iterable, items):
items = list(items) # get a list from any iterable and make our own copy
# since we modify it
if items:
items.sort()
for n, v in enumerate(iterable):
if n == items[0]:
yield v
items.pop(0)
if not items:
break
print list(getitems(open("/usr/share/dict/words"), [25, 29]))
# ['Abelson\n', 'Abernathy\n']
# note that index 25 is the 26th item
with open("test.txt", "r") as fp:
lines = fp.readlines()
print(lines[3])
test.txt는 파일 이름입니다.
테스트에서 4번째 행을 출력합니다.txt
이거 어때:
>>> with open('a', 'r') as fin: lines = fin.readlines()
>>> for i, line in enumerate(lines):
if i > 30: break
if i == 26: dox()
if i == 30: doy()
Import에 문제가 없는 경우 파일 입력이 필요한 작업을 수행합니다(이것은 현재 행의 행 번호를 읽을 수 있습니다).
저는 이 접근방식이 더 범용적이기 때문에 선호합니다. 즉, 파일 상에서 사용할 수 있습니다.f.readlines()
,에서StringIO
오브젝트, 모든 것:
def read_specific_lines(file, lines_to_read):
"""file is any iterable; lines_to_read is an iterable containing int values"""
lines = set(lines_to_read)
last = max(lines)
for n, line in enumerate(file):
if n + 1 in lines:
yield line
if n + 1 > last:
return
>>> with open(r'c:\temp\words.txt') as f:
[s for s in read_specific_lines(f, [1, 2, 3, 1000])]
['A\n', 'a\n', 'aa\n', 'accordant\n']
여기 내 작은 2센트가 있습니다.그만큼의 가치가 있습니다;)
def indexLines(filename, lines=[2,4,6,8,10,12,3,5,7,1]):
fp = open(filename, "r")
src = fp.readlines()
data = [(index, line) for index, line in enumerate(src) if index in lines]
fp.close()
return data
# Usage below
filename = "C:\\Your\\Path\\And\\Filename.txt"
for line in indexLines(filename): # using default list, specify your own list of lines otherwise
print "Line: %s\nData: %s\n" % (line[0], line[1])
Alok Singhal의 답변에 대한 더 좋고 작은 변화
fp = open("file")
for i, line in enumerate(fp,1):
if i == 26:
# 26th line
elif i == 30:
# 30th line
elif i > 30:
break
fp.close()
누군가가 이미 언급한 구문을 사용하여 이 작업을 수행할 수 있지만, 이것이 가장 쉬운 방법입니다.
inputFile = open("lineNumbers.txt", "r")
lines = inputFile.readlines()
print (lines[0])
print (lines[2])
꽤 빠르고 요점만 말해.
텍스트 파일에서 특정 행을 인쇄합니다."lines2print" 목록을 만든 다음 열거형이 lines2print 목록에 있을 때 인쇄합니다.추가 '\n'을 삭제하려면 line.strip() 또는 line.strip('\n')을 사용합니다.저는 그저 "목록 이해"를 좋아해서 가능하면 사용하려고 합니다.어떤 이유로든 파일을 열어두는 것을 방지하기 위해 텍스트 파일을 읽는 "with" 방식을 좋아합니다.
lines2print = [26,30] # can be a big list and order doesn't matter.
with open("filepath", 'r') as fp:
[print(x.strip()) for ei,x in enumerate(fp) if ei in lines2print]
또는 목록이 작으면 목록으로 이해에 입력하십시오.
with open("filepath", 'r') as fp:
[print(x.strip()) for ei,x in enumerate(fp) if ei in [26,30]]
파일 오브젝트에는 .readlines() 메서드가 있습니다.이 메서드는 파일 내용을 목록 항목별로 한 줄씩 보여줍니다.그런 다음 일반 목록 슬라이스 기술을 사용하면 됩니다.
http://docs.python.org/library/stdtypes.html#file.readlines
@OP, 열거를 사용할 수 있습니다.
for n,line in enumerate(open("file")):
if n+1 in [26,30]: # or n in [25,29]
print line.rstrip()
file = '/path/to/file_to_be_read.txt'
with open(file) as f:
print f.readlines()[26]
print f.readlines()[30]
with 문을 사용하면 파일이 열리고 줄 26과 30이 인쇄된 후 파일이 닫힙니다.심플!
행 번호 3을 인쇄하려면
line_number = 3
with open(filename,"r") as file:
current_line = 1
for line in file:
if current_line == line_number:
print(file.readline())
break
current_line += 1
원저작자: Frank Hofmann
원하는 라인을 인쇄합니다.필수 라인 위/아래에 라인을 인쇄합니다.
def dline(file,no,add_sub=0):
tf=open(file)
for sno,line in enumerate(tf):
if sno==no-1+add_sub:
print(line)
tf.close()
execute---->dline("D:\dummy.txt",6) 즉, dline("파일 경로", line_number. 검색된 행의 상위 행에 -1을 지정할 경우 이 값은 옵션 기본값입니다.)
특정 행(예를 들어 일부 임계값 행 뒤에 시작하는 행)을 읽으려면 다음 코드를 사용할 수 있습니다.file = open("files.txt","r") lines = file.readlines() ## convert to list of lines datas = lines[11:] ## raed the specific lines
사용 안 함readlines
!
나의 용도는 다음과 같다.
with open(filename) as f:
specify = [26, 30]
results = list(
map(lambda line: line[1],
filter(lambda line: line[0] in specify,
enumerate(f))
)
)
다음과 같이 테스트합니다.6.5G
파일:
import time
filename = 'a.txt'
start = time.time()
with open(filename, 'w') as f:
for i in range(10_000_000):
f.write(f'{str(i)*100}\n')
end1 = time.time()
with open(filename) as f:
specify = [26, 30]
results = list(
map(lambda line: line[1],
filter(lambda line: line[0] in specify,
enumerate(f))
)
)
end2 = time.time()
print(f'write time: {end1-start}')
print(f'read time: {end2-end1}')
# write time: 14.38945460319519
# read time: 8.380386352539062
배열 또는 목록에서 문자열을 분할하는 가장 간단한 논리 중 하나를 사용하여 이 작업을 수행할 수 있습니다.
f = open('filepath')
r = f.read()
s = r.split("\n")
n = [linenumber1, linenumber2] # [26, 29] in your
#case
for x in n:
print(s[x-1])
f.close()
f = open(filename, 'r')
totalLines = len(f.readlines())
f.close()
f = open(filename, 'r')
lineno = 1
while lineno < totalLines:
line = f.readline()
if lineno == 26:
doLine26Commmand(line)
elif lineno == 30:
doLine30Commmand(line)
lineno += 1
f.close()
이거면 될 것 같아
open_file1 = open("E:\\test.txt",'r')
read_it1 = open_file1.read()
myline1 = []
for line1 in read_it1.splitlines():
myline1.append(line1)
print myline1[0]
특정 행에서 읽기:
n = 4 # for reading from 5th line
with open("write.txt",'r') as t:
for i,line in enumerate(t):
if i >= n: # i == n-1 for nth line
print(line)
언급URL : https://stackoverflow.com/questions/2081836/how-to-read-specific-lines-from-a-file-by-line-number
'programing' 카테고리의 다른 글
mysql에서 그룹 이름 전 날짜 및 시간별로 주문 (0) | 2022.09.11 |
---|---|
python: 변수가 배열인지 스칼라인지 식별하는 방법 (0) | 2022.09.11 |
MySQL 8.x의 주요 버그 -- 외부 키 (0) | 2022.09.11 |
Java의 3차 연산자는 Java 7 이후 하나의 표현식만 평가합니다. Java 1.6 이하에서는 다른가요? (0) | 2022.09.11 |
MariaDB 10.3에서 특정 사용자에 대한 외부 액세스 허용 (0) | 2022.09.11 |