2014-08-28 2 views
-4

모든 줄을 계산하는 방법.파일을 읽고 모든 줄을 계산하십시오.

def file_size(filename): 
    infile = open(filename) 
    for line in infile: 
     return (len(line)) 
    infile.close() 

내 코드는 첫 번째 줄의 단어 수만 계산하므로 전체 파일 이름의 총 수를 계산해야합니다. 나는 이런 식으로 뭔가를 할 것

+6

당신은'return'이 무엇을 알고 있는가? – leon

+2

"모든 라인을 계산하라"는 의미는 무엇입니까? 모든 라인의 길이를 의미합니까? – SethMMorton

+1

그리고 행의 수 (또는 각 행의 길이의 합) 인 단일 숫자 또는 각 행의 길이를 포함하는 목록을 반환 하시겠습니까? – SethMMorton

답변

-2
>>> def file_size(filename): 
    infile = open(filename,'r') 
    count=0 
    total_line=0; 
    for line in infile: 
      total_line+=1 
      for i in line: 
        count+=1 
    infile.close() 
    return("Total Char = "+str(count) +" Total Lines = "+str(total_line)) 



>>> file_size("Cookie.py") 
'Total Char = 238 Total Lines = 5' 
+1

이것은 함수에서 반환 된 후 파일을 닫으려고 시도하기 때문에 좋은 답변이 아니므로 오해의 소지가 있거나 OP를 혼란스럽게합니다. – SethMMorton

1

:

def file_size(filename): 
    with open(filename) as f: 
     return sum(len(_.split()) for _ in f.readlines()) 
+1

'... in f'는 충분합니다. 여기에서'... f.readlines()'를 원하지 않습니다. – Matthias

+0

그리고'_'는 변수가 사용되지 않는 경우에만 일반적으로 사용됩니다 ... 여기에서 선의 길이를 얻기 위해 사용하고 있습니다. – SethMMorton

1
def file_size(filename): 
    lines = [] 
    with open(filename) as infile: 
     total = 0 
     for line_num, line in enumerate(infile, 1): 
      print("The length of line", line_num, "is", len(line)) 
      lines.append(len(line)) 
      total += 1 
     print("There are a total of", total, "lines") 
    return lines, total 
+1

나는 OP가 함수에서 총을 반환하고 싶다고 생각한다. – SethMMorton

+0

@SethMMorton : 그것은 OP의 게시물에서 명확하지 않았기 때문에 OP가 질문 할 것이라고 생각했던 두 질문에 모두 대답했습니다. – inspectorG4dget

+0

하지만이 함수는 '없음'을 반환합니다 ... 내 의견은 OP가 원했던 것 같아요. 그는 인쇄물이 아닌 * 함수에서 * 무엇인가를 반환합니다. – SethMMorton

관련 문제