본문 바로가기
파이썬

파이썬에서 파일을 반복하는 방법

by º기록 2020. 10. 4.
반응형

16 진수가 포함 된 텍스트 파일이 있는데이를 10 진수로 변환하려고합니다. 성공적으로 변환 할 수 있지만 루프가 존재하기 전에 원하지 않는 문자를 읽고 다음 오류가 발생합니다.

Traceback (most recent call last):
  File "convert.py", line 7, in <module>
    print >>g, int(x.rstrip(),16)
ValueError: invalid literal for int() with base 16: ''

내 코드는 다음과 같습니다.

f=open('test.txt','r')
g=open('test1.txt','w')
#for line in enumerate(f):  
while True:
    x=f.readline()
    if x is None: break
    print >>g, int(x.rstrip(),16)

각 16 진수는 입력을 위해 새 줄에 표시됩니다.

 

해결 방법

 

트레이스 백은 아마도 파일 끝에 빈 줄이 있음을 나타냅니다. 다음과 같이 수정할 수 있습니다.

f = open('test.txt','r')
g = open('test1.txt','w') 
while True:
    x = f.readline()
    x = x.rstrip()
    if not x: break
    print >> g, int(x, 16)

반면에 readline 대신 for x in f 를 사용하는 것이 좋습니다. 파일을 닫는 것을 잊지 말고 파일을 닫는 with 를 사용하는 것이 좋습니다.

with open('test.txt','r') as f:
    with open('test1.txt','w') as g: 
        for x in f:
            x = x.rstrip()
            if not x: continue
            print >> g, int(x, 16)

 

참조 페이지 https://stackoverflow.com/questions/5733419

 

 

반응형

댓글