programing

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

javaba 2022. 10. 27. 23:36
반응형

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

(이는 파르페가 다른 질문에 대답한 내용 중 일부입니다.)

# Open a connection to the file
with open('world_dev_ind.csv') as file:

    # Skip the column names
    file.readline()

    # Initialize an empty dictionary: counts_dict
    counts_dict = {}

    # Process only the first 1000 rows
    for j in range(0, 1000):

        # Split the current line into a list: line
        line = file.readline().split(',')

        # Get the value for the first column: first_col
        first_col = line[0]

        # If the column value is in the dict, increment its value
        if first_col in counts_dict.keys():
            counts_dict[first_col] += 1

        # Else, add to the dict and set value to 1
        else:
            counts_dict[first_col] = 1

# Print the resulting dictionary
print(counts_dict)

언급URL : https://stackoverflow.com/questions/4796764/read-file-from-line-2-or-skip-header-row

반응형