[python] 2 행에서 파일을 읽거나 헤더 행을 건너 뜁니다.

헤더 행을 건너 뛰고 line2에서 파일을 읽으려면 어떻게해야합니까?



답변

with open(fname) as f:
    next(f)
    for line in f:
        #do something


답변

f = open(fname,'r')
lines = f.readlines()[1:]
f.close()


답변

첫 번째 줄을 원하고 파일에서 일부 작업을 수행하려는 경우이 코드가 도움이 될 것입니다.

with open(filename , 'r') as f:
    first_line = f.readline()
    for line in f:
            # Perform some operations


답변

슬라이싱이 반복자에서 작동 할 수 있다면 …

from itertools import islice
with open(fname) as f:
    for line in islice(f, 1, None):
        pass


답변

f = open(fname).readlines()
firstLine = f.pop(0) #removes the first line
for line in f:
    ...


답변

여러 헤더 행을 읽는 작업을 일반화하고 가독성을 높이려면 메서드 추출을 사용합니다. coordinates.txt헤더 정보로 사용하기 위해 처음 세 줄을 토큰 화한다고 가정합니다 .

coordinates.txt
---------------
Name,Longitude,Latitude,Elevation, Comments
String, Decimal Deg., Decimal Deg., Meters, String
Euler's Town,7.58857,47.559537,0, "Blah"
Faneuil Hall,-71.054773,42.360217,0
Yellowstone National Park,-110.588455,44.427963,0

그런 방법 추출 지정할 수 있습니다 무엇을 당신이 헤더 정보와 함께 할 (이 예에서 우리는 단순히 쉼표에 따라 헤더 행을 토큰 화하고 목록으로 반환하지만 훨씬 더 많은 일을 할 수있는 공간이있다)하고 싶다.

def __readheader(filehandle, numberheaderlines=1):
    """Reads the specified number of lines and returns the comma-delimited
    strings on each line as a list"""
    for _ in range(numberheaderlines):
        yield map(str.strip, filehandle.readline().strip().split(','))

with open('coordinates.txt', 'r') as rh:
    # Single header line
    #print next(__readheader(rh))

    # Multiple header lines
    for headerline in __readheader(rh, numberheaderlines=2):
        print headerline  # Or do other stuff with headerline tokens

산출

['Name', 'Longitude', 'Latitude', 'Elevation', 'Comments']
['String', 'Decimal Deg.', 'Decimal Deg.', 'Meters', 'String']

coordinates.txt다른 헤더 라인 이 포함되어 있으면 간단히 변경하십시오 numberheaderlines. 무엇보다도 무엇 __readheader(rh, numberheaderlines=2)을하고 있는지는 분명 하며, 우리는 수용된 답변의 저자가 next()자신의 코드에서 사용하는 이유를 파악하거나 언급해야하는 모호성을 피합니다 .


답변

2 행부터 여러 CSV 파일을 읽으려면 매력처럼 작동합니다.

for files in csv_file_list:
        with open(files, 'r') as r:
            next(r)                  #skip headers             
            rr = csv.reader(r)
            for row in rr:
                #do something

(이것은 다른 질문에 대한 파르페의 답변의 일부입니다 )